Mastering Metasploit - Second Edition - Nipun Jaswal - E-Book

Mastering Metasploit - Second Edition E-Book

Nipun Jaswal

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Take your penetration testing and IT security skills to a whole new level with the secrets of Metasploit

About This Book

  • Gain the skills to carry out penetration testing in complex and highly-secured environments
  • Become a master using the Metasploit framework, develop exploits, and generate modules for a variety of real-world scenarios
  • Get this completely updated edition with new useful methods and techniques to make your network robust and resilient

Who This Book Is For

This book is a hands-on guide to penetration testing using Metasploit and covers its complete development. It shows a number of techniques and methodologies that will help you master the Metasploit framework and explore approaches to carrying out advanced penetration testing in highly secured environments.

What You Will Learn

  • Develop advanced and sophisticated auxiliary modules
  • Port exploits from PERL, Python, and many more programming languages
  • Test services such as databases, SCADA, and many more
  • Attack the client side with highly advanced techniques
  • Test mobile and tablet devices with Metasploit
  • Perform social engineering with Metasploit
  • Simulate attacks on web servers and systems with Armitage GUI
  • Script attacks in Armitage using CORTANA scripting

In Detail

Metasploit is a popular penetration testing framework that has one of the largest exploit databases around. This book will show you exactly how to prepare yourself against the attacks you will face every day by simulating real-world possibilities.

We start by reminding you about the basic functionalities of Metasploit and its use in the most traditional ways. You'll get to know about the basics of programming Metasploit modules as a refresher, and then dive into carrying out exploitation as well building and porting exploits of various kinds in Metasploit.

In the next section, you'll develop the ability to perform testing on various services such as SCADA, databases, IoT, mobile, tablets, and many more services. After this training, we jump into real-world sophisticated scenarios where performing penetration tests are a challenge. With real-life case studies, we take you on a journey through client-side attacks using Metasploit and various scripts built on the Metasploit framework.

By the end of the book, you will be trained specifically on time-saving techniques using Metasploit.

Style and approach

This is a step-by-step guide that provides great Metasploit framework methodologies. All the key concepts are explained details with the help of examples and demonstrations that will help you understand everything you need to know about Metasploit.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 319

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering Metasploit
Second Edition
Credits
Foreword
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Approaching a Penetration Test Using Metasploit
Organizing a penetration test
Preinteractions
Intelligence gathering/reconnaissance phase
Predicting the test grounds
Modeling threats
Vulnerability analysis
Exploitation and post-exploitation
Reporting
Mounting the environment
Setting up Kali Linux in virtual environment
The fundamentals of Metasploit
Conducting a penetration test with Metasploit
Recalling the basics of Metasploit
Benefits of penetration testing using Metasploit
Open source
Support for testing large networks and easy naming conventions
Smart payload generation and switching mechanism
Cleaner exits
The GUI environment
Penetration testing an unknown network
Assumptions
Gathering intelligence
Using databases in Metasploit
Modeling threats
Vulnerability analysis of VSFTPD 2.3.4 backdoor
The attack procedure
The procedure of exploiting the vulnerability
Exploitation and post exploitation
Vulnerability analysis of PHP-CGI query string parameter vulnerability
Exploitation and post exploitation
Vulnerability analysis of HFS 2.3
Exploitation and post exploitation
Maintaining access
Clearing tracks
Revising the approach
Summary
2. Reinventing Metasploit
Ruby – the heart of Metasploit
Creating your first Ruby program
Interacting with the Ruby shell
Defining methods in the shell
Variables and data types in Ruby
Working with strings
Concatenating strings
The substring function
The split function
Numbers and conversions in Ruby
Conversions in Ruby
Ranges in Ruby
Arrays in Ruby
Methods in Ruby
Decision-making operators
Loops in Ruby
Regular expressions
Wrapping up with Ruby basics
Developing custom modules
Building a module in a nutshell
The architecture of the Metasploit framework
Understanding the file structure
The libraries layout
Understanding the existing modules
The format of a Metasploit module
Disassembling existing HTTP server scanner module
Libraries and the function
Writing out a custom FTP scanner module
Libraries and the function
Using msftidy
Writing out a custom SSH authentication brute forcer
Rephrasing the equation
Writing a drive disabler post exploitation module
Writing a credential harvester post exploitation module
Breakthrough meterpreter scripting
Essentials of meterpreter scripting
Pivoting the target network
Setting up persistent access
API calls and mixins
Fabricating custom meterpreter scripts
Working with RailGun
Interactive Ruby shell basics
Understanding RailGun and its scripting
Manipulating Windows API calls
Fabricating sophisticated RailGun scripts
Summary
3. The Exploit Formulation Process
The absolute basics of exploitation
The basics
The architecture
System organization basics
Registers
Exploiting stack-based buffer overflows with Metasploit
Crashing the vulnerable application
Building the exploit base
Calculating the offset
Using the pattern_create tool
Using the pattern_offset tool
Finding the JMP ESP address
Using Immunity Debugger to find executable modules
Using msfbinscan
Stuffing the space
Relevance of NOPs
Determining bad characters
Determining space limitations
Writing the Metasploit exploit module
Exploiting SEH-based buffer overflows with Metasploit
Building the exploit base
Calculating the offset
Using pattern_create tool
Using pattern_offset tool
Finding the POP/POP/RET address
The Mona script
Using msfbinscan
Writing the Metasploit SEH exploit module
Using NASM shell for writing assembly instructions
Bypassing DEP in Metasploit modules
Using msfrop to find ROP gadgets
Using Mona to create ROP chains
Writing the Metasploit exploit module for DEP bypass
Other protection mechanisms
Summary
4. Porting Exploits
Importing a stack-based buffer overflow exploit
Gathering the essentials
Generating a Metasploit module
Exploiting the target application with Metasploit
Implementing a check method for exploits in Metasploit
Importing web-based RCE into Metasploit
Gathering the essentials
Grasping the important web functions
The essentials of the GET/POST method
Importing an HTTP exploit into Metasploit
Importing TCP server/ browser-based exploits into Metasploit
Gathering the essentials
Generating the Metasploit module
Summary
5. Testing Services with Metasploit
The fundamentals of SCADA
The fundamentals of ICS and its components
The significance of ICS-SCADA
Analyzing security in SCADA systems
Fundamentals of testing SCADA
SCADA-based exploits
Securing SCADA
Implementing secure SCADA
Restricting networks
Database exploitation
SQL server
Fingerprinting SQL server with Nmap
Scanning with Metasploit modules
Brute forcing passwords
Locating/capturing server passwords
Browsing SQL server
Post-exploiting/executing system commands
Reloading the xp_cmdshell functionality
Running SQL-based queries
Testing VOIP services
VOIP fundamentals
An introduction to PBX
Types of VOIP services
Self-hosted network
Hosted services
SIP service providers
Fingerprinting VOIP services
Scanning VOIP services
Spoofing a VOIP call
Exploiting VOIP
About the vulnerability
Exploiting the application
Summary
6. Virtual Test Grounds and Staging
Performing a penetration test with integrated Metasploit services
Interaction with the employees and end users
Gathering intelligence
Example environment under test
Vulnerability scanning with OpenVAS using Metasploit
Modeling the threat areas
Gaining access to the target
Vulnerability scanning with Nessus
Maintaining access and covering tracks
Managing a penetration test with Faraday
Generating manual reports
The format of the report
The executive summary
Methodology / network admin level report
Additional sections
Summary
7. Client-side Exploitation
Exploiting browsers for fun and profit
The browser autopwn attack
The technology behind a browser autopwn attack
Attacking browsers with Metasploit browser autopwn
Compromising the clients of a website
Injecting malicious web scripts
Hacking the users of a website
Conjunction with DNS spoofing
Tricking victims with DNS hijacking
Metasploit and Arduino - the deadly combination
File format-based exploitation
PDF-based exploits
Word-based exploits
Compromising Linux clients with Metasploit
Attacking Android with Metasploit
Summary
8. Metasploit Extended
The basics of post exploitation with Metasploit
Basic post exploitation commands
The help menu
Background command
Machine ID and UUID command
Reading from a channel
Getting the username and process information
Getting system information
Networking commands
File operation commands
Desktop commands
Screenshots and camera enumeration
Advanced post exploitation with Metasploit
Migrating to safer processes
Obtaining system privileges
Obtaining password hashes using hashdump
Changing access, modification and creation time with timestomp
Additional post exploitation modules
Gathering wireless SSIDs with Metasploit
Gathering Wi-Fi passwords with Metasploit
Getting applications list
Gathering skype passwords
Gathering USB history
Searching files with Metasploit
Wiping logs from target with clearev command
Advanced extended features of Metasploit
Privilege escalation using Metasploit
Finding passwords in clear text using mimikatz
Sniffing traffic with Metasploit
Host file injection with Metasploit
Phishing window login passwords
Summary
9. Speeding up Penetration Testing
Using pushm and popm commands
The loadpath command
Pacing up development using reload, edit and reload_all commands
Making use of resource scripts
Using AutoRunScript in Metasploit
Using multiscript module in AutoRunScript option
Globalizing variables in Metasploit
Automating Social-Engineering Toolkit
Summary
10. Visualizing with Armitage
The fundamentals of Armitage
Getting started
Touring the user interface
Managing the workspace
Scanning networks and host management
Modeling out vulnerabilities
Finding the match
Exploitation with Armitage
Post-exploitation with Armitage
Attacking on the client side with Armitage
Scripting Armitage
The fundamentals of Cortana
Controlling Metasploit
Post-exploitation with Cortana
Building a custom menu in Cortana
Working with interfaces
Summary
Further reading

Mastering Metasploit

Mastering Metasploit

Second Edition

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2014

Second edition: September 2016

Production reference: 1270916

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-316-6

www.packtpub.com

Credits

Authors

Nipun Jaswal

Copy Editor

Safis Editing

Reviewers

Adrian Pruteanu

Project Coordinator

Kinjal Bari 

Commissioning Editor

Kartikey Pandey

Proofreader

Safis Editing

Acquisition Editor

Prachi Bisht 

Indexer

Pratik Shirodkar 

Content Development Editor

Trusha Shriyan

Graphics

Kirk D'Penha

Technical Editor

Nirant Carvalho

Production Coordinator

Shantanu N. Zagade

Foreword

With the rising age of technology, the need for IT security has not only become a necessity but a practice that every organization must follow. Penetration testing is a practice that tends to keep businesses and organizations safe from the external and internal threats such as information leakage, unauthorized access to the various resources, critical business data and much more.

Companies providing services such as penetration testing and vulnerability assessments can be thought of as a group of people paid to break into a company so that no one else can break into it. However, the word penetration testing has a completely different meaning when it comes to law enforcement agencies throughout the world.

A Penetration test comprises of various different phases starting with profiling of the target through information gathering, scanning for open entrances which are also termed as port scanning, gaining access to the systems by exploiting vulnerable entrances, maintaining access to the target and covering tracks.

Zero day exploits and advanced persistent threats have recently dominated the cyber security scene throughout the world by compromising small to large firms by leaking crucial business data. Therefore, the life of a penetration tester has become quite challenging in terms of day to day operations and it is very important for a penetration tester to keep him updated with latest tools and techniques.

In this book, you will see penetration testing covered through a completely practical approach. The author is a widely known security professional with his experience ranging from the top of the corporate security structure all the way to the ground level research and exploit writing.

There are a number of books available on penetration testing, there are many covering specific security tools in penetration testing. This book is a perfect blend of both while covering the most widely used penetration testing framework, Metasploit, using a completely hands-on approach.

Metasploit is one of the most widely used penetration testing framework used from corporate to law enforcement agencies. Metasploit comprises of over 1500+ modules that deliver functionalities covering every phase of a penetration test, making the life of a penetration tester comparatively easier. Not only it provides a comprehensive and an efficient way of conducting a penetration test but being an open source framework, it also offers an extensive approach in developing new exploits and automating various tasks that reduce tons of manual efforts and saves a great deal of time.

With the support of a large community, Metasploit is constantly updated with new tools and techniques and is so frequently updated that a particular technique might change overnight. The author undertook a massive task in writing a book on a subject, which is so frequently updated. I believe you will find the techniques covered in this book valuable and an excellent reference in all your future engagements.

Maj. Gen. J.P Singh, Shaurya Chakra (Retd.)

M.Sc, MBA, MMS, M.Phill

Sr. Director, Amity University

About the Author

Nipun Jaswal is an IT security business executive & a passionate IT security Researcher with more than 7 years of professional experience and possesses knowledge in all aspects of IT security testing and implementation with expertise in managing cross-cultural teams and planning the execution of security needs beyond national boundaries.

He is an M.tech in Computer Sciences and a thought leader who has contributed in raising the bar of understanding on cyber security and ethical hacking among students of many colleges and universities in India. He is a voracious public speaker, delivers speech on Improving IT Security, Insider Threat, Social Engineering, Wireless forensics, and Exploit writing. He is the author of numerous IT security articles with popular security magazines like Eforensics, Hakin9, and Security Kaizen etc. Many popular companies like Apple, Microsoft, AT&T, Offensive Security, Rapid7, Blackberry, Nokia, Zynga.com and many others have thanked him for finding vulnerabilities in their system. He has also been acknowledged with the Award of excellence from National cyber defense and research center (NCDRC) for his tremendous contributions to the IT security industry.

In his current profile, he leads team super specialists in cyber security to protect various clients from Cyber Security threats and network intrusion by providing necessary solutions and services. Please feel free to contact him via mail at [email protected].

At the very first, I would like to thank everyone who read the first edition and made it a success. I would like to thank my mom, Mrs. Sushma Jaswal and my grandmother, Mrs. Malkiet Parmar for helping me out at every stage of my life. I would also like to extend gratitude to Ms. Mini Malhotra for being extremely supportive throughout the writing process. I would like to thank Mr. Adrian Pruteanu for reviewing my work and suggesting all the changes. I would like to thank everyone at Packt including Ms. Prachi Bisht, Ms. Trusha Shriyan for being an excellent team and providing me with opportunity to work on this wonderful project. Last but not the least; I would like to thank the almighty for providing me with the immense power to work on this project.

About the Reviewer

Adrian Pruteanu is a senior consultant who specializes in penetration testing and reverse engineering. With over 10 years of experience in the security industry, Adrian has provided services to all major financial institutions in Canada, as well as countless other companies around the world. You can find him on Twitter as @waydrian, or on his seldom updated blog https://bittherapy.net.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

"In the Memory of all our brave soldiers who lost their lives serving for the country." 

Preface

Penetration testing is the one necessity required everywhere in business today. With the rise of cyber- and computer-based crime in the past few years, penetration testing has become one of the core aspects of network security and helps in keeping a business secure from internal as well as external threats. The reason that makes penetration testing a necessity is that it helps in uncovering the potential flaws in a network, a system, or an application. Moreover, it helps in identifying weaknesses and threats from an attacker's perspective. Various potential flaws in a system are exploited to find out the impact it can cause to an organization and the risk factors to the assets as well. However, the success rate of a penetration test depends largely on the knowledge of the target under the test. Therefore, we generally approach a penetration test using two different methods: black box testing and white box testing. Black box testing refers to the testing where there is no prior knowledge of the target under test. Therefore, a penetration tester kicks off testing by collecting information about the target systematically. Whereas in the case of a white box penetration test, a penetration tester has enough knowledge about the target under test and he starts off by identifying known and unknown weaknesses of the target. Generally, a penetration test is divided into seven different phases, which are mentioned as follows:

Pre-engagement interactions: This phase defines all the pre-engagement activities and scope definitions, basically, everything you need to discuss with the client before the testing starts.Intelligence gathering: This phase is all about collecting information about the target, which is under the test, by connecting to the target directly and passively, without connecting to the target at all.Threat modeling: This phase involves matching the information detected to the assets in order to find the areas with the highest threat level.Vulnerability analysis: This involves finding and identifying known and unknown vulnerabilities and validating them.Exploitation: This phase works on taking advantage of the vulnerabilities found in the previous phase. This typically means that we are trying to gain access to the target.Post exploitation: The actual task to perform at the target that involves downloading a file, shutting a system down, creating a new user account on the target, and so on, are parts of this phase. Generally, this phase describes what you need to do after exploitation.Reporting: This phase includes summing up the results of the test under a file and the possible suggestions and recommendations to fix the current weaknesses in the target

The seven phases just mentioned may look easier when there is a single target under test. However, the situation completely changes when a large network that contains hundreds of systems are to be tested. Therefore, in a situation like this, manual work is to be replaced with an automated approach. Consider a scenario where the number of systems under the test is exactly 100 and are running the same operating system and services. Testing each and every system manually will consume much time and energy. Situations like these demand the use of a penetration-testing framework. The use of a penetration testing framework will not only save time, but will also offer much more flexibility in terms of changing the attack vectors and covering a much wider range of targets under a test. A penetration testing framework will eliminate additional time consumption and will  also help in automating most of the attack vectors; scanning processes; identifying vulnerabilities, and most importantly, exploiting the vulnerabilities, thus saving time and pacing a penetration test. This is where Metasploit kicks in.

Metasploit is considered as one of the best and most used widely used penetration testing framework. With a lot of rep in the IT security community, Metasploit not only caters to the needs of being a great penetration test framework but also delivers such innovative features that make life of a penetration tester easy.

Mastering Metasploit aims at providing readers with the insights to the most popular penetration-testing framework, that is, Metasploit. This book specifically focuses on mastering Metasploit in terms of exploitation, writing custom exploits, porting exploits, testing services, and conducting sophisticated client-side testing. Moreover, this book helps to convert your customized attack vectors into Metasploit modules, covering Ruby, and attack scripting, such as CORTANA. This book will not only caters to your penetration-testing knowledge, but will also help you build programming skills as well.

What this book covers

Chapter 1, Approaching a Penetration Test Using Metasploit, tells you concisely about WebStorm 10 and its new features. It helps you install it, guides you through its workspace, discusses setting up a new project, familiarizes you with the interface and useful features, and describes the ways to customize them to suit your needs.

Chapter 2, Reinventing Metasploit, exposes the most distinctive features of WebStorm, which are at the core of improving your efficiency in building web applications.

Chapter 3, The Exploit Formulation Process, describes the process of setting up a new project with the help of templates by importing an existing project, serving a web application, and using File Watchers.

Chapter 4, Porting Exploits, describes using package managers and building systems for your application by means of WebStorm's built-in features.

Chapter 5, Testing Services with Metasploit, focuses on the state-of-the-art technologies of the web industry and describes the process of building a typical application in them using the power of WebStorm features.

Chapter 6, Virtual Test Grounds and Staging, shows you how to use JavaScript, HTML, and CSS to develop a mobile application and how to set up the environment to test run this mobile application.

Chapter 7, Client-side Exploitation, shows how to perform the debugging, tracing, profiling, and code style checking activities directly in WebStorm.

Chapter 8, Metasploit Extended, presents a couple of proven ways to easily perform application testing in WebStorm using some of the most popular testing libraries.

Chapter 9, Speeding up Penetration Testing, is about a second portion of powerful features provided within WebStorm. In this chapter, we focus on some of WebStorm's power features that help us boost productivity and developer experience.

Chapter 10, Visualizing with Armitage, is about a second portion of powerful features provided within WebStorm. In this chapter, we focus on some of WebStorm's power features that help us boost productivity and developer experience.

What you need for this book

To follow and recreate the examples in this book, you will need six to seven systems. One can be your penetration testing system, whereas others can be the systems under test. Alternatively, you can work on a single system and set up a virtual environment.

Apart from systems or virtualization, you will need the latest ISO of Kali Linux, which already packs Metasploit by default and contains all the other tools that are required for recreating the examples of this book.

You will also need to install Ubuntu, Windows XP, Windows 7, and Windows Server 2008, Windows Server 2012, Metasploitable 2 and Windows 10 either on virtual machines or live systems as all these operating systems will serve as the test bed for Metasploit.

Additionally, links to all other required tools and vulnerable software are provided in the chapters.

Who this book is for

This book is a hands-on guide to penetration testing using Metasploit and covers its complete development. It shows a number of techniques and methodologies that will help you master the Metasploit framework and explore approaches to carrying out advanced penetration testing in highly secured environments.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1.  Approaching a Penetration Test Using Metasploit

"In God I trust, all others I pen-test" - Binoj Koshy, cyber security expert

Penetration testing is an intentional attack on a computer-based system with the intention of finding vulnerabilities, figuring out security weaknesses, certifying that a system is secure, and gaining access to the system by exploiting these vulnerabilities. A penetration test will advise an organization if it is vulnerable to an attack, whether the implemented security is enough to oppose any attack, which security controls can be bypassed, and so on. Hence, a penetration test focuses on improving the security of an organization.

Achieving success in a penetration test largely depends on using the right set of tools and techniques. A penetration tester must choose the right set of tools and methodologies in order to complete a test. While talking about the best tools for penetration testing, the first one that comes to mind is Metasploit. It is considered one of the most effective auditing tools to carry out penetration testing today. Metasploit offers a wide variety of exploits, an extensive exploit development environment, information gathering and web testing capabilities, and much more.

This book has been written so that it will not only cover the frontend perspectives of Metasploit, but it will also focus on the development and customization of the framework as well. This book assumes that the reader has basic knowledge of the Metasploit framework. However, some of the sections of this book will help you recall the basics as well.

While covering Metasploit from the very basics to the elite level, we will stick to a step-by-step approach, as shown in the following diagram:

This chapter will help you recall the basics of penetration testing and Metasploit, which will help you warm up to the pace of this book.

In this chapter, you will learn about the following topics:

The phases of a penetration testThe basics of the Metasploit frameworkThe workings of exploitsTesting a target network with MetasploitThe benefits of using databases

An important point to take a note of here is that we might not become an expert penetration tester in a single day. It takes practice, familiarization with the work environment, the ability to perform in critical situations, and most importantly, an understanding of how we have to cycle through the various stages of a penetration test.

When we think about conducting a penetration test on an organization, we need to make sure that everything is set perfectly and is according to a penetration test standard. Therefore, if you feel you are new to penetration testing standards or uncomfortable with the term Penetration testing Execution Standard (PTES), please refer to http://www.pentest-standard.org/index.php/PTES_Technical_Guidelines to become more familiar with penetration testing and vulnerability assessments. According to PTES, the following diagram explains the various phases of a penetration test:

Refer to the http://www.pentest-standard.org website to set up the hardware and systematic phases to be followed in a work environment; these setups are required to perform a professional penetration test.

Organizing a penetration test

Before we start firing sophisticated and complex attack vectors with Metasploit, we must get ourselves comfortable with the work environment. Gathering knowledge about the work environment is a critical factor that comes into play before conducting a penetration test. Let us understand the various phases of a penetration test before jumping into Metasploit exercises and see how to organize a penetration test on a professional scale.

Preinteractions

The very first phase of a penetration test, preinteractions, involves a discussion of the critical factors regarding the conduct of a penetration test on a client's organization, company, institute, or network; this is done with the client. This serves as the connecting line between the penetration tester and the client. Preinteractions help a client get enough knowledge on what is about to be done over his or her network/domain or server. Therefore, the tester will serve here as an educator to the client. The penetration tester also discusses the scope of the test, all the domains that will be tested, and any special requirements that will be needed while conducting the test on the client's behalf. This includes special privileges, access to critical systems, and so on. The expected positives of the test should also be part of the discussion with the client in this phase. As a process, preinteractions discuss some of the following key points:

Scope: This section discusses the scope of the project and estimates the size of the project. Scope also defines what to include for testing and what to exclude from the test. The tester also discusses ranges and domains under the scope and the type of test (black box or white box) to be performed. For white box testing, what all access options are required by the tester? Questionnaires for administrators, the time duration for the test, whether to include stress testing or not, and payment for setting up the terms and conditions are included in the scope. A general scope document provides answers to the following questions:What are the target organization's biggest security concerns?What specific hosts, network address ranges, or applications should be tested?What specific hosts, network address ranges, or applications should explicitly NOT be tested?Are there any third parties that own systems or networks that are in the scope, and which systems do they own (written permission must have been obtained in advance by the target organization)?Will the test be performed against a live production environment or a test environment?Will the penetration test include the following testing techniques: ping sweep of network ranges, port scan of target hosts, vulnerability scan of targets, penetration of targets, application-level manipulation, client-side Java/ActiveX reverse engineering, physical penetration attempts, social engineering?Will the penetration test include internal network testing? If so, how will access be obtained?Are client/end-user systems included in the scope? If so, how many clients will be leveraged?Is social engineering allowed? If so, how may it be used?Are Denial of Service attacks allowed?Are dangerous checks/exploits allowed?Goals: This section discusses various primary and secondary goals that a penetration test is set to achieve. The common questions related to the goals are as follows:
What is the business requirement for this penetration test?
This is required by a regulatory audit or standardProactive internal decision to determine all weaknesses
What are the objectives?
Map out vulnerabilitiesDemonstrate that the vulnerabilities existTest the incident responseActual exploitation of a vulnerability in a network, system, or applicationAll of the above
Testing terms and definitions: This section discusses basic terminologies with the client and helps him or her understand the terms well.Rules of engagement: This section defines the time of testing, timeline, permissions to attack, and regular meetings to update the status of the ongoing test. The common questions related to rules of engagement are as follows:
At what time do you want these tests to be performed?
During business hoursAfter business hoursWeekend hoursDuring a system maintenance window
Will this testing be done on a production environment?If production environments should not be affected, does a similar environment (development and/or test systems) exist that can be used to conduct the penetration test?Who is the technical point of contact?

For more information on preinteractions, refer to http://www.pentest-standard.org/index.php/File:Pre-engagement.png.

Intelligence gathering/reconnaissance phase

In the intelligence-gathering phase, you need to gather as much information as possible about the target network. The target network could be a website, an organization, or might be a full-fledged Fortune 500 company. The most important aspect is to gather information about the target from social media networks and use Google Hacking (a way to extract sensitive information from Google using specialized queries) to find sensitive information related to the target. Footprinting the organization using active and passive attacks can also be an approach.

The intelligence phase is one of the most crucial phases in penetration testing. Properly gained knowledge about the target will help the tester to stimulate appropriate and exact attacks, rather than trying all possible attack mechanisms; it will also help him or her save a large amount of time as well. This phase will consume 40 to 60 percent of the total time of the testing, as gaining access to the target depends largely upon how well the system is footprinted.

It is the duty of a penetration tester to gain adequate knowledge about the target by conducting a variety of scans, looking for open ports, identifying all the services running on those ports and to decide which services are vulnerable and how to make use of them to enter the desired system.

The procedures followed during this phase are required to identify the security policies that are currently set in place at the target, and what we can do to breach them.

Let us discuss this using an example. Consider a black box test against a web server where the client wants to perform a network stress test.

Here, we will be testing a server to check what level of bandwidth and resource stress the server can bear or in simple terms, how the server is responding to the Denial of Service (DoS) attack. A DoS attack or a stress test is the name given to the procedure of sending indefinite requests or data to a server in order to check whether the server is able to handle and respond to all the requests successfully or crashes causing a DoS. A DoS can also occur if the target service is vulnerable to specially crafted requests or packets. In order to achieve this, we start our network stress-testing tool and launch an attack towards a target website. However, after a few seconds of launching the attack, we see that the server is not responding to our browser and the website does not open. Additionally, a page shows up saying that the website is currently offline. So what does this mean? Did we successfully take out the web server we wanted? Nope! In reality, it is a sign of protection mechanism set by the server administrator that sensed our malicious intent of taking the server down, and hence resulting in a ban of our IP address. Therefore, we must collect correct information and identify various security services at the target before launching an attack.

The better approach is to test the web server from a different IP range. Maybe keeping two to three different virtual private servers for testing is a good approach. In addition, I advise you to test all the attack vectors under a virtual environment before launching these attack vectors onto the real targets. A proper validation of the attack vectors is mandatory because if we do not validate the attack vectors prior to the attack, it may crash the service at the target, which is not favorable at all. Network stress tests should generally be performed towards the end of the engagement or in a maintenance window. Additionally, it is always helpful to ask the client for white listing IP addresses used for testing.

Now let us look at the second example. Consider a black box test against a windows 2012 server. While scanning the target server, we find that port 80 and port 8080 are open. On port 80, we find the latest version of Internet Information Services (IIS) running while on port 8080, we discover that the vulnerable version of the Rejetto HFS Server is running, which is prone to the remote code execution (RCE) flaw.

However, when we try to exploit this vulnerable version of HFS, the exploit fails. This might be a common scenario where inbound malicious traffic is blocked by the firewall.

In this case, we can simply change our approach to connecting back from the server, which will establish a connection from the target back to our system, rather than us connecting to the server directly. This may prove to be more successful as firewalls are commonly being configured to inspect ingress traffic rather than egress traffic.

Coming back to the procedures involved in the intelligence-gathering phase when viewed as a process are as follows:

Target selection