Metasploit Penetration Testing Cookbook, Second Edition

By Monika Agarwal , Abhinav Singh
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Metasploit Quick Tips for Security Professionals

About this book

Metasploit software helps security and IT professionals identify security issues, verify vulnerability mitigations, and manage expert-driven security assessments. Capabilities include smart exploitation, password auditing, web application scanning, and social engineering. Teams can collaborate in Metasploit and present their findings in consolidated reports. The goal of the software is to provide a clear understanding of the critical vulnerabilities in any environment and to manage those risks.

Metasploit Penetration Testing Cookbook, Second Edition contains chapters that are logically arranged with an increasing level of complexity and thoroughly covers some aspects of Metasploit, ranging from pre-exploitation to the post-exploitation phase. This book is an update from version 4.0 to version 4.5. It covers the detailed penetration testing techniques for different specializations like wireless networks, VOIP systems, and the cloud.

Metasploit Penetration Testing Cookbook, Second Edition covers a number of topics which were not part of the first edition. You will learn how to penetrate an operating system (Windows 8 penetration testing) to the penetration of a wireless network, VoIP network, and then to cloud.

The book starts with the basics, such as gathering information about your target, and then develops to cover advanced topics like building your own framework scripts and modules. The book goes deep into operating-systems-based penetration testing techniques and moves ahead with client-based exploitation methodologies. In the post-exploitation phase, it covers meterpreter, antivirus bypass, ruby wonders, exploit building, porting exploits to the framework, and penetration testing, while dealing with VOIP, wireless networks, and cloud computing.

This book will help readers to think from a hacker's perspective to dig out the flaws in target networks and also to leverage the powers of Metasploit to compromise them. It will take your penetration skills to the next level.

Publication date:
October 2013


Chapter 1. Metasploit Quick Tips for Security Professionals

In this chapter, we will cover:

  • Configuring Metasploit on Windows

  • Configuring Metasploit on Ubuntu

  • Installing Metasploit with BackTrack 5 R3

  • Setting up the penetration testing using VMware

  • Setting up Metasploit on a virtual machine with SSH connectivity

  • Installing and configuring PostgreSQL in Backtrack 5 R3

  • Using the database to store the penetration testing results

  • Working with BBQSQL



Metasploit is currently the most buzzing word in the field of information security and penetration testing. It has totally revolutionized the way we can perform security tests on our systems. The reason which makes Metasploit so popular is the wide range of tasks that it can perform to ease the work of penetration testing to make systems more secure. Metasploit is available for all popular operating systems. The working process of the framework is almost the same for all of them. Here in this book, we will primarily work on BackTrack 5 OS as it comes with the preinstalled Metasploit framework and other third-party tools which run over the framework.

The Penetration Testing Execution Standard (PTES) has redefined the penetration test in ways that will be influencing both fresh and experienced penetration testers, and it has been exercised by various leading members of the security community.

The phases of PTES are designed to describe a penetration test and assure the client community that a standardized level of endeavor will be extended in a penetration test. This standard is categorized into seven categories:

  • Pre-engagement interactions: They generally occur when we discuss the scope and conditions of the penetration test with the client. It is damn crucial during pre-engagement that we convey the objectives of the engagement clearly. This phase also serves as an opportunity to educate the customer about what is to be expected from a penetration test, without restrictions regarding what can and will be tested during the engagement.

  • Intelligence gathering: In the intelligence gathering phase, we will be gathering any information we can about the target under the attack by using social media networks, Google hacking, footprinting the target, and much more. One of the most important skills a penetration tester can have is the ability to learn about a target, including how it functions, how it operates, and how it ultimately can be compromised. The information that is gathered about the target will give deep insight into the kinds of security controls in place. During this phase, an attempt is made to identify what protection techniques are in place at the target by trying to probe it. For example, an organization will often only allow traffic on a certain subset of ports on externally facing devices, and if anyone queries the organization on anything other than a white-listed port, they will be blocked. It is generally a nice notion to test this blocking kind of a behavior by initially probing from an expendable IP address that is intended to have blocked or detected. The same stands true when testing web applications, where the web application firewalls will block one from making further requests.

  • Threat modeling: Threat modeling makes use of the information acquired in the previous phase to determine any well-known vulnerabilities on a target system. When performing threat modeling, it will result in finding the most effective attack method, the type of information desired, and how the organization might be breached. Threat modeling often includes observing an organization as an adversary, and approaches to exploit weaknesses as a malicious user would.

  • Vulnerability analysis: Having bagged with the most viable attack methods, now we will focus to gain access on the target machine. During vulnerability analysis, aggregate the information that has been learned from prior phases and consume it to determine what attacks might be fruitful. Vulnerability analysis takes into account even ports and vulnerability scans, data obtained from banner grabbing, and intelligence gathering, among other things.

  • Exploitation: Exploitation is probably one of the most fascinating parts of a penetration test, although it is often performed with brute force instead of precision. An exploit should be executed only when attacker knows almost beyond a shadow of a doubt that a particular exploit will work. For sure, unforeseen protective measures may be in place on the target that stops a particular exploit from working—but before we trigger a vulnerability, it must be ensured that the system is vulnerable. Blindly firing off a bulk of exploits and desiring for a shell isn't productive.

  • Post exploitation: The post exploitation phase begins after a system or more than one system is being compromised, but is not even close to being fully done yet. Post exploitation is a critical part in any of the penetration tests. This is where we distinguish ourselves from the average, run-of-the-mill hacker and actually gives valuable information and knowledge from the penetration test. It actually targets particular systems, identifies critical structures, and targets information or data that the industry values most and that it has attempted to secure. When we exploit one machine after another,, we are actually trying to illustrate the attacks that would have the greatest business impact factor. When attacking systems in the post exploitation phase, it may take time depending upon the system and the user's aim.

Let us proceed with a quick introduction to the framework and the various terminologies related to it:

  • Metasploit framework: It is a free, open source penetration testing framework started by H. D. Moore in 2003, which was later acquired by Rapid7. The current stable versions of the framework are written using the Ruby language. It has the world's largest database of tested exploits and receives more than a million downloads every year. It is also one of the most complex projects built in Ruby to date.

  • Vulnerability: It is a weakness which allows an attacker/pentester to break into or compromise a system's security. This weakness can either exist in the operating system, application software, or even in the network protocols.

  • Exploit: Exploit is a code which allows an attacker/tester to take advantage of the vulnerable system and compromise its security. Every vulnerability has its own corresponding exploit. Metasploit v4 has more than 700 exploits.

  • Payload: It is the actual code which does the work. It runs on the system after exploitation. They are mostly used to set up a connection between the attacking and the victim machine. Metasploit v4 has more than 250 payloads.

  • Module: Modules are the small building blocks of a complete system. Every module performs a specific task and a complete system is built by combining several modules to function as a single unit. The biggest advantage of such an architecture is that it becomes easy for developers to integrate a new exploit code and tools into the framework.

The Metasploit framework has a modular architecture and the exploits, payload, encoders, and so on are considered separate modules:

Let us examine the architecture diagram closely.

Metasploit uses different libraries which hold the key to the proper functioning of the framework. These libraries are a collection of predefined tasks, operations, and functions that can be utilized by different modules of the framework. The most fundamental part of the framework is the Ruby Extension (Rex) library. Some of the components provided by Rex include a wrapper socket subsystem, implementations of protocol clients and servers, a logging subsystem, exploitation utility classes, and a number of other useful classes. Rex itself is designed to have no dependencies, other than what comes with the default Ruby installation.

Then, we have the MSF Core library which extends Rex. Core is responsible for implementing all of the required interfaces that allow for interacting with exploit modules, sessions, and plugins. This core library is extended by the framework base library, which is designed to provide simpler wrapper routines for dealing with the framework core, as well as providing utility classes for dealing with different aspects of the framework, such as serializing a module state to different output formats. Finally, the base library is extended by the framework's User Interface (UI) that implements support for the different types of user interfaces to the framework itself, such as the command console and the web interface.

There are four different user interfaces provided with the framework, namely: msfconsole , msfcli , msfgui , and msfweb . It is highly encouraged that one should check out all these different interfaces, but in this book, we will primarily work on the msfconsole interface. This is because msfconsole provides the best support to the framework, leveraging all of the functionalities.

The msfconsole interface is by far the most talked about part of the Metasploit framework, and for good reason, as it is one of the most ductile, character-rich, and well-supported tools within the framework. It actually provides a handy all-in-one interface to every choice and setting attainable in the framework; it's like a one-stop shop for all of pentesting dreams. We can use msfconsole to do anything, including launching an exploit, loading auxiliary, executing enumeration, producing listeners, or executing mass exploitation in contrast to an entire network.

The msfcli and msfconsole interfaces take very different attempts for providing access to the framework. Unlike msfconsole, which provides an interactive way to access all facilities in a user-amicably manner, msfcli puts the priority on scripting and interpretability with aggregation to console-based tools. Instead of providing an individual interpreter to the framework, it runs directly from the command-line interface, which allows us to redirect results from other tools into msfcli and direct that msfcli output to other command-line tools. In addition, msfcli also supports the launching of exploits and auxiliaries, and it can be more convenient when modules or developing new exploits for the framework are tested.

The msfGUI interface of Metasploit is a completely interactive GUI created by Raphael Mudge. This interface is highly affectionate, feature-rich, and can be availed for free.

Let us now move to the recipes of this chapter and practically analyze the various aspects.


Configuring Metasploit on Windows

Installation of the Metasploit framework on Windows is simple and requires almost noeffort. The framework installer can be downloaded from the Metasploit official website ( In this recipe, we will learn how to configure Metasploit on the Windows operating system.

Getting ready

You will notice that there are two types of installer available for Windows. It is recommended to download the complete installer of the Metasploit framework, which contains the console and all other relevant dependencies, along with the database and runtime setup. In case you already have a configured database that you want to use for the framework as well, then you can go for the mini installer of the framework, which only installs the console and dependencies.

How to do it...

Once you have completed downloading the installer, simply run it and sit back. It will automatically install all the relevant components and set up the database for you. Once the installation is complete, you can access the framework through various shortcuts created by the installer.

How it works...

You will find that the installer has created lots of shortcuts for you. Most of the things are click-and-go in a Windows environment. Some of the options you will find are Metasploit web, cmd console, Metasploit update, and so on.


While installing Metasploit on Windows, you should disable the antivirus protection, as it may detect some of the installation files as potential viruses or threats and can block the installation process. Once the installation is complete, make sure that you have white-listed the framework installation directory in your antivirus, as it will detect the exploits and payloads as malicious.

There's more…

Now, let's talk about some other options, or possibly some pieces of general information, that are relevant to installing the Metasploit framework on Windows explicitly.

Database error during installation

There is a common problem with many users while installing the Metasploit framework on the Windows machine. While running the setup, you may encounter an error message, as shown in the following screenshot:

This is the result of an error in configuring the PostgreSQL server. The possible causes are:

  • PostgreSQL not running: Use Netstat to figure out if the port is open and the database is running.

  • Some installers require a default installation path. For example, if the default path is C drive, changing it to the D drive will give this error.

  • Language encoding: If you face this problem, you can overcome it by downloading the simpler version of the framework, which contains only the console and dependencies. Then, configure the database manually and connect it with Metasploit.


Configuring Metasploit on Ubuntu

The Metasploit framework has full support for Ubuntu-based Linux operating systems. In this recipe, we will be covering the installation process, which is a bit different from that of Windows.

Getting ready

Download the setup from the official Metasploit website (

How to do it...

The process for installing a full setup is as follows:

  • We will need to execute the following commands to install the framework on our Ubuntu machine:

    chmod +x
    You will get the text of the license in a bunch of pages, then:
    Do you accept this license? [y/n]: y
    Select a folder [/opt/metasploit]:
    Install Metasploit as a service? [Y/n]:
    Service script name: [metasploit]:
    SSL Port [3790]:
    Server Name []:
    Days of validity [3650]:
    Database Server port [7337]:
    Setup is now ready to begin installing Metasploit on your computer.
    Do you want to continue? [Y/n]:
    Please wait while Setup installs Metasploit on your computer.
    0% ______________ 50% ______________ 100%
    Setup has finished installing Metasploit on your computer.
    Info: To access Metasploit, go to
            https://localhost:3790 from your browser.
    Press [Enter] to continue 


    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

There's more...

Now, let's talk about some other options, or possibly some pieces of general information that are relevant to this task.

Cloning the Metasploit framework

We can opt for cloning the Metasploit framework from GitHub using the following command:

$ git clone git:// /opt/metasploit/msf3


Cloning the Metasploit framework from GitHub will, no doubt, give you the Metasploit framework. But, it will not install required dependencies, configure a database, or give you access to the web-based Metasploit community.

Error during installation

After installing the full setup, all seems to be set now. When we type https://localhost:3790 in our browser, it will show the following error:

Looking up localhost:3790
Making HTTPS connection to localhost:3790
Alert!: Unable to connect to remote host.
Even if we try to run createuser, it will result as :
/opt/metasploit/apps/pro/ui/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.11/l ib/active_support/dependencies.rb:251:in 'require': /usr/lib/ version 'LIBXML2_2.9.0' not found (required by /opt/metasploit/common/lib/ - /opt/metasploit/apps/pro/ui/vendor/bundle/ruby/1.9.1/gems/nokogiri-1.5.2/lib/no kogiri/ (LoadError)
        from /opt/metasploit/apps/pro/ui/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.11/ lib/active_support/dependencies.rb:251:in 'block in require'
        from /opt/metasploit/apps/pro/ui/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.11/ lib/active_support/dependencies.rb:236:in 'load_dependency'
        from /opt/metasploit/apps/pro/ui/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.11/ lib/active_support/dependencies.rb:251:in 'require'
        from /opt/metasploit/apps/pro/ui/vendor/bundle/ruby/1.9.1/gems/nokogiri-1.5.2/lib/no kogiri.rb:27:in '<top (required)>'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler/runtime .rb:68:in 'require'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler/runtime .rb:68:in 'block (2 levels) in require'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler/runtime .rb:66:in 'each'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler/runtime .rb:66:in 'block in require'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler/runtime .rb:55:in 'each'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler/runtime .rb:55:in 'require'
        from /opt/metasploit/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.1.2/lib/bundler.rb:119: in 'require'
        from /opt/metasploit/apps/pro/ui/script/createuser:14:in '<main>'

So to get rid of this problem, check the download page for Metasploit 4.5.2, as this problem is fixed in this version. And, when you download it again, use the --version option to confirm that you downloaded the new version.


Installing Metasploit with BackTrack 5 R3

BackTrack is the most popular operating system for security professionals for two reasons. First, it has all the popular penetration testing tools preinstalled in it, so it reduces the cost of a separate installation. Secondly, it is a Linux-based operating system, which makes it less prone to virus attacks and provides more stability during penetration testing. It saves you time from installing relevant components and tools, and who knows when you may encounter an unknown error during the installation process. So, let's move on with installation of BackTrack 5 R3.

Getting ready

Either you can have a separate installation of BackTrack on your hard disk or you can also use it over a host on a virtual machine. The installation process is simple and the same as installing any Linux-based operating system.

How to do it...

The following steps show the entire process of installing BackTrack 5 R3:

  1. When booting the BackTrack OS, you will be asked to enter the username and password. The default username for the root user is root and the password is toor.

  2. Upon successful login, you can either work over the command line or enter startx to enter in the GUI mode.

  3. You can either start the Metasploit framework from the Applications menu or from the command line. To launch Metasploit from the Applications menu, go to Applications | BackTrack | Exploitation Tools | Network Exploitation Tools | Metasploit Framework, as shown in the following screenshot:

  4. Metasploit follows a simple directory structure hierarchy where the root folder is pentest. The directory further branches to /exploits/framework3. To launch Metasploit from the command line, launch the terminal and enter the following command to move to the Metasploit directory:

    [email protected]:~# cd /pentest/exploits/framework3
    [email protected]:/pentest/exploits/framework3 ~# ./msfconsole

How it works...

Launching Metasploit from the command line will follow the complete path to msfconsole. Launching it from the Application menu will provide us with direct access to different UIs available to us.

There's more

Most people would like to upgrade their existing system instead of engaging in an all new installation. Fortunately, people who have BackTrack 5 R2 as their current OS can easily upgrade it to R3. Let us see how to do this.

Upgrading from R2 to R3

For those who don't want to start with the new installation, they can easily upgrade their existing installation of R2 to R3.

First, we must make sure our current system is fully updated:

apt – get update && apt – get dist upgrade

The execution of this command will result in the installation of the new tools that have been added for R3. Keeping in mind the system architecture, one must choose the right one.

32-bit tools

For installation on a 32-bit system, use the following command:

apt-get install libcrafter blueranger dbd inundator intersect mercury cutycapt trixd00r artemisa rifiuti2 netgear-telnetenable jboss-autopwn deblaze sakis3g voiphoney apache-users phrasendrescher kautilya manglefizz rainbowcrack rainbowcrack-mt lynis-audit spooftooph wifihoney twofi truecrack uberharvest acccheck statsprocessor iphoneanalyzer jad javasnoop mitmproxy ewizard multimac netsniff-ng smbexec websploit dnmap johnny unix-privesc-check sslcaudit dhcpig intercepter-ng u3-pwn binwalk laudanum wifite tnscmd10g bluepot dotdotpwn subterfuge jigsaw urlcrazy creddump android-sdk apktool ded dex2jar droidbox smali termineter bbqsql htexploit smartphone-pentest-framework fern-wifi-cracker powersploit webhandler
64-bit tools

For installation on a 64-bit system, use the following command:

apt-get install libcrafter blueranger dbd inundator intersect mercury cutycapt trixd00r rifiuti2 netgear-telnetenable jboss-autopwn deblaze sakis3g voiphoney apache-users phrasendrescher kautilya manglefizz rainbowcrack rainbowcrack-mt lynis-audit spooftooph wifihoney twofi truecrack acccheck statsprocessor iphoneanalyzer jad javasnoop mitmproxy ewizard multimac netsniff-ng smbexec websploit dnmap johnny unix-privesc-check sslcaudit dhcpig intercepter-ng u3-pwn binwalk laudanum wifite tnscmd10g bluepot dotdotpwn subterfuge jigsaw urlcrazy creddump android-sdk apktool ded dex2jar droidbox smali termineter multiforcer bbqsql htexploit smartphone-pentest-framework fern-wifi-cracker powersploit webhandler

Setting up penetration testing using VMware

You can always have a penetration testing lab set up by using multiple machines; it is considered the ideal setup. But, what if you have an emergency where you immediately need to set up a testing scenario and you only have a single machine? Well, using a virtual machine is the obvious answer. You can work simultaneously on more than one operating system and perform the task of penetration testing. So, let us have a quick look at how we can set up a penetration testing lab on a single system with the help of a virtual machine.

Getting ready

We will be using a VMWare workstation 9 to set up two virtual machines with BackTrack 5 R3 and Windows XP SP2 operating systems. Our host system is a Windows 7 machine. We will need the VMware installer and either an image file or an installation disk of the two operating systems we want to set up in the virtual machine. So, our complete setup will consist of a host system running Windows 7 with two virtual systems running BackTrack 5 R3 and Windows XP SP2, respectively.


VirtualBox or Qemo are open source alternatives to VMWare, since VMWare is a paid application.

How to do it...

The process of installing a virtual machine is simple and self-explanatory. Follow these steps:

  1. After installing the VMware, create a new virtual machine. Select the appropriate options and click on Next. You will have to provide an installation medium to start the setup. The medium can either be an image file or installation disk. For a complete manual on a virtual machine and installation procedure, you can visit the following link:

  2. For a better virtual machine performance, it is recommended to have at least 4 GB of available RAM for a 32-bit operating system and 8 GB RAM for 64-bit operating system. In the next recipe, I will show you a cool way to bring down your memory usage while running multiple virtual machines.

  3. Once the virtual machine (VM) is created, you can use the clone option. This will create an exact copy of your VM, so in case some failure occurs in your operating VM, you can switch to the cloned VM without worrying about reinstalling it. Also, you can use the Snapshot... option to save the current state of your VM. Snapshot... will save the current working settings of your virtual machine and you can revert back to your saved snapshot anytime in the future.

Before you start your virtual machines, there is an important configuration that we will have to make in order to make the two virtual machines communicate with each other. Select one of the virtual machines and click on Settings. Then, move to Network settings. In the Network Adapter option, there will be a preinstalled NAT adapter for the Internet usage of the host machine. Under Network connection, select Host-only adapter. Follow this process for both the virtual machines:

How it works...

The reason for setting up a Host-only adapter is to make the two virtual machines communicate with each other. Now, in order to test whether everything is fine, check the IP address of the Windows virtual machine by entering ipconfig in the command prompt. Now, ping the Windows machine (using the local IP address obtained from the ipconfig command) from the BackTrack machine to see if it is receiving the packets or not. Follow the process vice versa to cross-check both the machines.

There's more...

Now, let's talk about some other options, or possibly some pieces of general information that are relevant to this task.

Disabling the firewall and antivirus protection

There can be situations when we may find that while pinging the Windows machine from the BackTrack machine, the packets are not received. This can possibly be due to the default Windows firewall setting. So, disable the firewall protection and ping again to see if the packets are getting received or not. Also, disable any firewall that may be installed in the virtual machine.


Setting up Metasploit on a virtual machine with SSH connectivity

In the previous recipe, we focused on setting up a penetration testing lab on a single machine with the help of virtualization. But, there can be serious memory usage concerns while using multiple virtual machines. So, here we will discuss a conservation technique which can be really handy in bad times.

Getting ready

All we need is an SSH client. We will use PuTTY as it is the most popular and free SSH client available for Windows. We will set up an SSH connectivity with the BackTrack machine, as it has more memory consumption than the Windows XP machine.

How to do it...

  1. We will start by booting our BackTrack virtual machine. Upon reaching the login prompt, enter the credentials to start the command line. Now, don't start the GUI. Execute any one of the following commands:

    [email protected]:~# /etc/init.d/ ssh  start 
    [email protected]:~# start ssh

    This will start the SSH process on the BackTrack machine.

  2. Now, find the IP address of the machine by entering the following command:

    [email protected]:~# ifconfig

    Note down this IP address.

  3. Now, start PuTTY on the host operating system. Enter the IP address of the BackTrack virtual machine and enter port 22:

  4. Now, click on Open to launch the command line. If the connection is successful, you will see the PuTTY command line functioning on behalf of the BackTrack machine. It will ask you to log in. Enter the credentials and enter ifconfig to check if the IP is the same as that of the virtual BackTrack:

How it works...

In this SSH session, we can now interact with the BackTrack virtual machine using PuTTY. As the GUI is not loaded, it reduces the memory consumption by almost half. Also, minimizing the BackTrack virtual machine will further reduce memory consumption, as the Windows operating system provides less memory share to the processes that are minimized and provides faster execution of those tasks that are running in maximized mode. This will further reduce the memory consumption to some extent.


You will need to verify the SSH certificate after you launch the connection.


Installing and configuring PostgreSQL in BackTrack 5 R3

An important feature of Metasploit is the presence of databases, which you can use to store your penetration testing results. Any penetration test consists of lots of information and can run for several days, so it becomes essential to store the intermediate results and findings. A good penetration testing tool should have proper database integration to store the results quickly and efficiently. In this recipe, we will be dealing with the installation and configuration process of a database in BackTrack 5 R3.

Getting ready

Metasploit comes with PostgreSQL as the default database. Let us first check out the default settings of the PostgreSQL database. We will have to navigate to database.yml, located under opt/framework3/config. To do this, run the following command:

[email protected]:~# cd /opt/metasploit/config
[email protected]:/opt/metasploit/config# cat database.yml
adapter: postgresql
database: msf3
username: msf3
password: 8b826ac0
port: 7175
pool: 75
timeout: 5

Notice the default username, password, and default database that has been created. Note down these values, as they will be required further along. You can also change these values according to your preference, as well.

How to do it...

Now, our job is to connect the database and start using it. Let us launch the msfconsole interface and see how we can set up the databases and store our results.

Let us first check the available database drivers:

msf > db_driver
[*]Active Driver: postgresql
[*]Available: postgresql, mysql


Rapid7 has dropped the support for MySQL database in the recent versions of Metasploit, so the db_driver command may not work. The only default driver supported with the framework in that case will be PostgreSQL.

How it works...

To connect the driver to msfconsle, we will be using the db_connect command. This command will be executed using the following syntax:

db_connect username:[email protected]:port number/database_name

Here, we will use the same default values of the username, password, database name, and port number, which we just noted from the database.yml file:

msf > db_connect msf3:[email protected]:7175/msf3

On successful execution of the command, our database is fully configured.

There's more...

Let us discuss some more important facts related to setting up the database.

Getting an error while connecting to the database

There are chances of an error while trying to establish the connection. There are two things to keep in mind if any error arises:

  • Check the db_driver and db_connect commands and make sure that you are using the correct combination of the database.

  • Use start/etc/init.d to start the database service and then try connecting it.


    Another troubleshooting tip is to change the msfconsole interface start script (/opt/metasploit/msf3/msfconsole) to include the correct Ruby Parser (#!/opt/metasploit/ruby/bin/ruby). Some database functions, such as db_connect will not work if this is not done.

If the error still prevails, we can reinstall the database and associated libraries using the following commands:

msf> gem install postgres
msf> apt-get install libpq-dev 

Deleting the database

At anytime, you can drop the created database and start again to store fresh results. The following command can be executed for deleting the database:

msf> db_destroy msf3:[email protected]:7175/msf3
Database "msf3" dropped.

Using the database to store the penetration testing results

Let us now learn how we can use our configured database to store our results of the penetration tests.

Getting ready

If you have successfully executed the previous recipe, you are all set to use the database for storing the results. Enter the help command in msfconsole to have a quick look at the important database commands available to us.

How to do it...

Let us start with a quick example. The db_nmap command stores the results of the port scan directly into the database, along with all relevant information.

  1. Launch a simple Nmap scan on the target machine to see how it works:

    msf > db_nmap
    [*] Nmap: Starting Nmap 5.51SVN ( ) at 2011-10-04 20:03 IST
    [*] Nmap: Nmap scan report for
    [*] Nmap: Host is up (0.0012s latency)
    [*] Nmap: Not shown: 997 closed ports
    [*] Nmap: 135/tcp open  msrpc
    [*] Nmap: 139/tcp open  netbios-ssn
    [*] Nmap: 445/tcp open  microsoft-ds
    [*] Nmap: MAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems)
    [*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 1.94 seconds

    As we can see, Nmap has produced the scan results and it will automatically populate the msf3 database that we are using.

  2. We can also use the –oX parameter in the Nmap scan to store the result in XML format. This will be very beneficial for us to import the scan results in other third-party software, such as the Dradis framework, which we will be analyzing in the next chapter:

    msf > nmap –A -oX report
    [*] exec: nmap –A -oX report
    Starting Nmap 5.51SVN ( ) at 2011-10-05 11:57 IST
    Nmap scan report for
    Host is up (0.0032s latency)
    Not shown: 997 closed ports
    135/tcp open  msrpc
    139/tcp open  netbios-ssn
    445/tcp open  microsoft-ds
    MAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems)
    Nmap done: 1 IP address (1 host up) scanned in 0.76 seconds

    Here, report is the name of the file where our scanned result will be stored.


Working with BBQSQL

BBQSQL is an open source SQL injection framework written in Python, specially made to be hyper fast and database agnostic. The BBQSQL tool was developed by Ben Toews in Python. The most fascinating feature of this tool is that it can exploit blind SQL injection vulnerability. This is very useful tool to check the web application's security and then patch exposed vulnerabilities found by the tool. Let's start working with BBQSQL with the following steps:

  1. The first step will be setting up parameters. It consists of many parameters that we can configure while setting up an attack:

    • files: It provides files to be sent along with the request.

    • headers: This can be a string or a dictionary sent with the request. {"User-Agent":"bbqsql"} or "User-Agent: bbqsql".

    • cookies: A dictionary or string sent along with cookies. {"PHPSESSIONID":"123123"} or PHPSESSIONID=123123;JSESSIONID=foobar.

    • url: This specifies a URL that the requests should be sent to.

    • allow redirects: This is a Boolean[value] that determines whether HTTP redirects will be followed when making requests.

    • proxies: This specifies an HTTP proxy to be used for the request as a dictionary. {"http": "","https": ""}.

    • data: This specifies post data to be sent along with the request. This can be a string or a dictionary.

    • method: This specifies the method for the HTTP request (for example, get, options, head, post, put, patch, delete).

    • auth: This specifies a tuple of a username and password to be used for HTTP basic authentication.

    • ("myusername","mypassword")

  2. Secondly, we will set up BBQSQL options. They are:

    • Query: The query input is where we will construct our query used to exfiltrate data from the database. The assumption is that we already have identified SQL injection on a vulnerable parameter, and have tested a query that is successful. In this example, the attacker is looking to select the database version:

      vulnerable_parameter'; if(ASCII(SUBSTRING((SELECT @@version LIMIT 1 OFFSET ${row_index}) , ${char_index} ,1))) ${comparator:>}ASCII(${char_val}) WAITFOR DELAY '0\:0\:0${sleep}'; --
    • The csv_output file: This is the name of a file to output the results to. Leave this blank if you don't want output to a file.

    • technique: We can specify either binary_search or frequency_search as the value for this parameter.

    • Comparison_attr: This specifies the type of SQL injection you have discovered. Here, you can set which attribute of the HTTP response BBQSQL should look at to determine true/false. You can specify: status_code, URL, time, size, text, content, encoding, cookies, headers, or history.

  3. Then, move on to Export Config. After we have set up the attack, we can export the configuration file. We will see the option while running the tool. The exported configuration file actually uses ConfigParser, which is easy to read. An example configuration file is as follows:

    '[Request Config] url =${injection} method = GET [HTTP Config] query = ' and ASCII(SUBSTR((SELECT data FROM data LIMIT 1 OFFSET ${row_index:1}),${char_index:1},1))${comparator:>}${char_val:0} # technique = binary_search comparison_attr = size concurrency = 30'
  4. Let us see how we can import Config. We can import a configuration file from the command line or from the user interface:

    bbqsql –c config_file


    When we load a config file either via command line or the user interface, the same validation routines are applied on the parameters to ensure that they are valid.

  5. Finally, we will run the exploit by selecting option 5, and the exploit will run. We can export attack results as a csv file.

The BBQSQL framework installer can be downloaded from BBQSQL uses two techniques while executing an attack. They are as follows:

  1. Binary search: This technique is used by default. We can specify details of characters in the row or the queue to be used, and information regarding the targeted character in a row.

  2. Frequency search: It is based on an analysis of the English language to determine the frequency of the occurrence of a letter. This search method works fast against nonentropic data, but can be slow against non-English or obfuscated data.

How to do it...

To work with BBQSQL, use the following instructions:

  1. Install BBQSQL using the following command:

    sudo pip install bbqsql
  2. On a fresh BackTrack 5 R3, install pip is not available. The user will need to run the following to install pip:

    sudo apt-get install python-pip
  3. Type bbqsql and press Enter to start BBQSQL.

While working with BBQSQL, the screen will look like the following screenshot:

How it works...

The injection can work on any of the following:

  • URL: "$ {query}"

  • data: "user=foo&pass=$ {query}"

  • cookies: {'PHPSESSID' : '123123 ' , ' foo ' , ' BAR $ {query}'}

BBQSQL UI is built using the source from the Social-Engineer Toolkit (SET). We do not have to wait until we type a huge request on the command-line interface, as it pre-ensures that an input validation is performed on each and every configuration option.

About the Authors

  • Monika Agarwal

    Monika Agarwal is a young Information Security Researcher from India. She has presented many research papers at both national and international conferences. She is a member of IAENG (International Association of Engineers). Her main areas of interest are ethical hacking and ad hoc networking.

    Browse publications by this author
  • Abhinav Singh

    Abhinav Singh is a well-known information security researcher. He is the author of Metasploit Penetration Testing Cookbook (first and second editions) and Instant Wireshark Starter, by Packt. He is an active contributor to the security community—paper publications, articles, and blogs. His work has been quoted in several security and privacy magazines, and digital portals. He is a frequent speaker at eminent international conferences—Black Hat and RSA. His areas of expertise include malware research, reverse engineering, enterprise security, forensics, and cloud security.

    Browse publications by this author
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial