Ruby and Metasploit Modules

Exclusive offer: get 50% off this eBook here
Mastering Metasploit

Mastering Metasploit — Save 50%

Write and implement sophisticated attack vectors in Metasploit using a completely hands-on approach with this book and ebook

$29.99    $15.00
by Nipun Jaswal | May 2014 | Open Source

In this article, by Nipun Jaswal, the author of Mastering Metasploit, we will cover the basics of Ruby programming and understand the various syntaxes and semantics of it. This article will also make it easy for you to write Metasploit modules. We will see how we can design and fabricate various custom Metasploit modules.

(For more resources related to this topic, see here.)

Reinventing Metasploit

Consider a scenario where the systems under the scope of the penetration test are very large in number, and we need to perform a post-exploitation function such as downloading a particular file from all the systems after exploiting them. Downloading a particular file from each system manually will consume a lot of time and will be tiring as well. Therefore, in a scenario like this, we can create a custom post-exploitation script that will automatically download a file from all the systems that are compromised.

This article focuses on building programming skill sets for Metasploit modules. This article kicks off with the basics of Ruby programming and ends with developing various Metasploit modules. In this article, we will cover the following points:

  • Understanding the basics of Ruby programming

  • Writing programs in Ruby programming

  • Exploring modules in Metasploit

  • Writing your own modules and post-exploitation modules

Let's now understand the basics of Ruby programming and gather the required essentials we need to code Metasploit modules.

Before we delve deeper into coding Metasploit modules, we must know the core features of Ruby programming that are required in order to design these modules. However, why do we require Ruby for Metasploit? The following key points will help us understand the answer to this question:

  • Constructing an automated class for reusable code is a feature of the Ruby language that matches the needs of Metasploit

  • Ruby is an object-oriented style of programming

  • Ruby is an interpreter-based language that is fast and consumes less development time

  • Earlier, Perl used to not support code reuse

Ruby – the heart of Metasploit

Ruby is indeed the heart of the Metasploit framework. However, what exactly is Ruby? According to the official website, Ruby is a simple and powerful programming language. Yokihiru Matsumoto designed it in 1995. It is further defined as a dynamic, reflective, and general-purpose object-oriented programming language with functions similar to Perl.

You can download Ruby for Windows/Linux from http://rubyinstaller.org/downloads/.

You can refer to an excellent resource for learning Ruby practically at http://tryruby.org/levels/1/challenges/0.

Creating your first Ruby program

Ruby is an easy-to-learn programming language. Now, let's start with the basics of Ruby. However, remember that Ruby is a vast programming language. Covering all the capabilities of Ruby will push us beyond the scope of this article. Therefore, we will only stick to the essentials that are required in designing Metasploit modules.

Interacting with the Ruby shell

Ruby offers an interactive shell too. Working on the interactive shell will help us understand the basics of Ruby clearly. So, let's get started. Open your CMD/terminal and type irb in it to launch the Ruby interactive shell.

Let's input something into the Ruby shell and see what happens; suppose I type in the number 2 as follows:

irb(main):001:0> 2 => 2

The shell throws back the value. Now, let's give another input such as the addition operation as follows:

irb(main):002:0> 2+3 => 5

We can see that if we input numbers using an expression style, the shell gives us back the result of the expression.

Let's perform some functions on the string, such as storing the value of a string in a variable, as follows:

irb(main):005:0> a= "nipun" => "nipun" irb(main):006:0> b= "loves metasploit" => "loves metasploit"

After assigning values to the variables a and b, let's see what the shell response will be when we write a and a+b on the shell's console:

irb(main):014:0> a => "nipun" irb(main):015:0> a+b => "nipunloves metasploit"

We can see that when we typed in a as an input, it reflected the value stored in the variable named a. Similarly, a+b gave us back the concatenated result of variables a and b.

Defining methods in the shell

A method or function is a set of statements that will execute when we make a call to it. We can declare methods easily in Ruby's interactive shell, or we can declare them using the script as well. Methods are an important aspect when working with Metasploit modules. Let's see the syntax:

def method_name [( [arg [= default]]...[, * arg [, &expr ]])] expr end

To define a method, we use def followed by the method name, with arguments and expressions in parentheses. We also use an end statement following all the expressions to set an end to the method definition. Here, arg refers to the arguments that a method receives. In addition, expr refers to the expressions that a method receives or calculates inline. Let's have a look at an example:

irb(main):001:0> def week2day(week) irb(main):002:1> week=week*7 irb(main):003:1> puts(week) irb(main):004:1> end => nil

We defined a method named week2day that receives an argument named week. Further more, we multiplied the received argument with 7 and printed out the result using the puts function. Let's call this function with an argument with 4 as the value:

irb(main):005:0> week2day(4) 28 => nil

We can see our function printing out the correct value by performing the multiplication operation. Ruby offers two different functions to print the output: puts and print. However, when it comes to the Metasploit framework, the print_line function is used.

Variables and data types in Ruby

A variable is a placeholder for values that can change at any given time. In Ruby, we declare a variable only when we need to use it. Ruby supports numerous variables' data types, but we will only discuss those that are relevant to Metasploit. Let's see what they are.

Working with strings

Strings are objects that represent a stream or sequence of characters. In Ruby, we can assign a string value to a variable with ease as seen in the previous example. By simply defining the value in quotation marks or a single quotation mark, we can assign a value to a string.

It is recommended to use double quotation marks because if single quotations are used, it can create problems. Let's have a look at the problem that may arise:

irb(main):005:0> name = 'Msf Book' => "Msf Book" irb(main):006:0> name = 'Msf's Book' irb(main):007:0' '

We can see that when we used a single quotation mark, it worked. However, when we tried to put Msf's instead of the value Msf, an error occurred. This is because it read the single quotation mark in the Msf's string as the end of single quotations, which is not the case; this situation caused a syntax-based error.

The split function

We can split the value of a string into a number of consecutive variables using the split function. Let's have a look at a quick example that demonstrates this:

irb(main):011:0> name = "nipun jaswal" => "nipun jaswal" irb(main):012:0> name,surname=name.split(' ') => ["nipun", "jaswal"] irb(main):013:0> name => "nipun" irb(main):014:0> surname => "jaswal"

Here, we have split the value of the entire string into two consecutive strings, name and surname by using the split function. However, this function split the entire string into two strings by considering the space to be the split's position.

The squeeze function

The squeeze function removes extra spaces from the given string, as shown in the following code snippet:

irb(main):016:0> name = "Nipun Jaswal" => "Nipun Jaswal" irb(main):017:0> name.squeeze => "Nipun Jaswal"

Numbers and conversions in Ruby

We can use numbers directly in arithmetic operations. However, remember to convert a string into an integer when working on user input using the .to_i function. Simultaneously, we can convert an integer number into a string using the .to_s function.

Let's have a look at some quick examples and their output:

irb(main):006:0> b="55" => "55" irb(main):007:0> b+10 TypeError: no implicit conversion of Fixnum into String from (irb):7:in `+' from (irb):7 from C:/Ruby200/bin/irb:12:in `<main>' irb(main):008:0> b.to_i+10 => 65 irb(main):009:0> a=10 => 10 irb(main):010:0> b="hello" => "hello" irb(main):011:0> a+b TypeError: String can't be coerced into Fixnum from (irb):11:in `+' from (irb):11 from C:/Ruby200/bin/irb:12:in `<main>' irb(main):012:0> a.to_s+b => "10hello"

We can see that when we assigned a value to b in quotation marks, it was considered as a string, and an error was generated while performing the addition operation. Nevertheless, as soon as we used the to_i function, it converted the value from a string into an integer variable, and addition was performed successfully. Similarly, with regards to strings, when we tried to concatenate an integer with a string, an error showed up. However, after the conversion, it worked.

Ranges in Ruby

Ranges are important aspects and are widely used in auxiliary modules such as scanners and fuzzers in Metasploit.

Let's define a range and look at the various operations we can perform on this data type:

irb(main):028:0> zero_to_nine= 0..9 => 0..9 irb(main):031:0> zero_to_nine.include?(4) => true irb(main):032:0> zero_to_nine.include?(11) => false irb(main):002:0> zero_to_nine.each{|zero_to_nine| print(zero_to_nine)} 0123456789=> 0..9 irb(main):003:0> zero_to_nine.min => 0 irb(main):004:0> zero_to_nine.max => 9

We can see that a range offers various operations such as searching, finding the minimum and maximum values, and displaying all the data in a range. Here, the include? function checks whether the value is contained in the range or not. In addition, the min and max functions display the lowest and highest values in a range.

Arrays in Ruby

We can simply define arrays as a list of various values. Let's have a look at an example:

irb(main):005:0> name = ["nipun","james"] => ["nipun", "james"] irb(main):006:0> name[0] => "nipun" irb(main):007:0> name[1] => "james"

So, up to this point, we have covered all the required variables and data types that we will need for writing Metasploit modules.

For more information on variables and data types, refer to the following link:

http://www.tutorialspoint.com/ruby/

Refer to a quick cheat sheet for using Ruby programming effectively at the following links:

https://github.com/savini/cheatsheets/raw/master/ruby/RubyCheat.pdf

http://hyperpolyglot.org/scripting

Methods in Ruby

A method is another name for a function. Programmers with a different background than Ruby might use these terms interchangeably. A method is a subroutine that performs a specific operation. The use of methods implements the reuse of code and decreases the length of programs significantly. Defining a method is easy, and their definition starts with the def keyword and ends with the end statement. Let's consider a simple program to understand their working, for example, printing out the square of 50:

def print_data(par1) square = par1*par1 return square end answer=print_data(50) print(answer)

The print_data method receives the parameter sent from the main function, multiplies it with itself, and sends it back using the return statement. The program saves this returned value in a variable named answer and prints the value.

Decision-making operators

Decision making is also a simple concept as with any other programming language. Let's have a look at an example:

irb(main):001:0> 1 > 2 => false irb(main):002:0> 1 < 2 => true

Let's also consider the case of string data:

irb(main):005:0> "Nipun" == "nipun" => false irb(main):006:0> "Nipun" == "Nipun" => true

Let's consider a simple program with decision-making operators:

#Main num = gets num1 = num.to_i decision(num1) #Function def decision(par1) print(par1) par1= par1 if(par1%2==0) print("Number is Even") else print("Number is Odd") end end

We ask the user to enter a number and store it in a variable named num using gets. However, gets will save the user input in the form of a string. So, let's first change its data type to an integer using the to_i method and store it in a different variable named num1. Next, we pass this value as an argument to the method named decision and check whether the number is divisible by two. If the remainder is equal to zero, it is concluded that the number is divisible by true, which is why the if block is executed; if the condition is not met, the else block is executed.

The output of the preceding program will be something similar to the following screenshot when executed in a Windows-based environment:

Mastering Metasploit Write and implement sophisticated attack vectors in Metasploit using a completely hands-on approach with this book and ebook
Published: May 2014
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Loops in Ruby

Iterative statements are called loops; exactly like any other programming language, loops also exist in Ruby programming. Let's use them and see how their syntax differs from other languages:

def forl for i in 0..5 print("Number #{i}\n") end end forl

The preceding code iterates the loop from 0 to 5 as defined in the range and consequently prints out the values. Here, we have used #{i} to print the value of the i variable in the print statement. The \n keyword specifies a new line. Therefore, every time a variable is printed, it will occupy a new line.

Refer to http://www.tutorialspoint.com/ruby/ruby_loops.htm for more on loops.

Regular expressions

Regular expressions are used to match a string or its number of occurrences in a given set of strings or a sentence. The concept of regular expressions is critical when it comes to Metasploit. We use regular expressions in most cases while writing fuzzers, scanners, analyzing the response from a given port, and so on.

Let's have a look at an example of a program that demonstrates the usage of regular expressions.

Consider a scenario where we have a variable, n, with the value Hello world, and we need to design regular expressions for it. Let's have a look at the following code snippet:

irb(main):001:0> n = "Hello world" => "Hello world" irb(main):004:0> r = /world/ => /world/ irb(main):005:0> r.match n => #<MatchData "world"> irb(main):006:0> n =~r => 6

We have created another variable called r and we stored our regular expression in it, that is, world. In the next line, we match the regular expression with the string using the match object of the MatchData class. The shell responds with a message saying yes it matches by displaying MatchData "world". Next, we will use another approach of matching a string using the =~ operator and receiving the exact location of the match. Let's see one other example of doing this:

irb(main):007:0> r = /^world/ => /^world/ irb(main):008:0> n =~r => nil irb(main):009:0> r = /^Hello/ => /^Hello/ irb(main):010:0> n =~r => 0 irb(main):014:0> r= /world$/ => /world$/ irb(main):015:0> n=~r => 6

Let's assign a new value to r, namely, /^world/; here, the ^ operator tells the interpreter to match the string from the start. We get nil as the output as it is not matched. We modify this expression to start with the word Hello; this time, it gives us back the location zero, which denotes a match as it starts from the very beginning. Next, we modify our regular expression to /world$/, which denotes that we need to match the word world from the end so that a successful match is made.

For further information on regular expressions in Ruby, refer to http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm.

Refer to a quick cheat sheet for using Ruby programming effectively at the following links:

https://github.com/savini/cheatsheets/raw/master/ruby/RubyCheat.pdf

http://hyperpolyglot.org/scripting

Refer to http://rubular.com/ for more on building correct regular expressions.

Wrapping up with Ruby basics

Hello! Still awake? It was a tiring session, right? We have just covered the basic functionalities of Ruby that are required to design Metasploit modules. Ruby is quite vast, and it is not possible to cover all its aspects here. However, refer to some of the excellent resources on Ruby programming from the following links:

Developing custom modules

Let's dig deep into the process of writing a module. Metasploit has various modules such as payloads, encoders, exploits, NOPs, and auxiliaries. We will cover the essentials of developing a module; then, we will look at how we can actually create our own custom modules.

Let's discuss the essentials of building a module first.

Building a module in a nutshell

Let's understand how things are arranged in the Metasploit framework as well as what all the components of Metasploit are and what they are meant to do.

The architecture of the Metasploit framework

Metasploit is composed of various components. These components include all the important libraries, modules, plugins, and tools. A diagrammatic view of the structure of Metasploit is as follows:

Let's see what these components are and how they work. The best to start with are the Metasploit libraries that act as the heart of Metasploit.

Let's understand the use of various libraries as explained in the following table:

Library name

Uses

REX

Handles almost everything, from basic socket, setting up sockets, connections and formatting, almost for everything we need

MSF CORE

Provides the basic API and the actual core that describes the framework

MSF BASE

Provides friendly API support to modules

We have different types of modules in Metasploit, and they differ in terms of their functionality. We have payloads modules for creating an access channel to the exploited system. We have auxiliary modules to carry out operations such as information gathering, fingerprinting, fuzzing an application, and logging in to various services. Let's examine the basic functionality of these modules, as shown in the following table:

Module type

Working

Payloads

This is used to carry out operations such as connecting to or from the target system after exploitation, or performing a specific task such as installing a service and so on.

Payload execution is the next step after a system gets exploited successfully. The widely used meterpreter shell is a common Metasploit payload.

Auxiliary

Auxiliary modules are special kind of modules that perform specific tasks. Tasks such as information gathering, database fingerprinting, scanning the network in order to find a particular service and enumeration, and so on, are the common operations of auxiliary modules.

Encoders

These are used to encrypt payloads and the attack vectors to avoid detection by antiviruses or firewalls.

NOPs

NOPs' usage makes the payloads stable.

Exploits

The actual code that triggers to take advantage of a vulnerable system.

Understanding the libraries' layout

Metasploit modules are the buildup of various functions contained in different libraries and the general Ruby programming. Now, to use these functions, first we need to understand what these functions are. How can we trigger these functions? What number of parameters do we need to pass? Moreover, what will these functions return?

Let's have a look at where these libraries are actually located; this is illustrated in the following screenshot:

As we can see in the preceding screenshot, we have the REX libraries located in the /lib directory; under the /msf folder, we have the /base and /core library directories.

Now, under the core libraries' folder, we have libraries for all the modules we covered earlier; this is illustrated in the following screenshot:

We will get started with writing our very first auxiliary module shortly. So, let's focus on the auxiliary modules first and check what is under the hood. Looking into the library for auxiliary modules, we will find that we have various library files to perform a variety of tasks, as shown in the following screenshot:

These library files provide the core for auxiliary modules. However, for different operations and functionalities, we can refer to any library we want. Some of the most widely used library files in most Metasploit modules are located in the core/exploits/directory, as shown in the following screenshot:

We can find all other core libraries for various types of modules in the core/ directory. Currently, we have core libraries for exploits, payload, post-exploitation, encoders, and various other modules.

Visit the Metasploit Git repository at https://github.com/rapid7/metasploit-framework to access the complete source code.

Summary

In this article, we learned how Ruby is the heart of the Metasploit framework. We learned to create Ruby programs and interacted with the Ruby shell as well. We also learned about how to define methods in the Ruby shell and about various variables and data types of Ruby. Finally, we also learned how to develop custom modules in Metasploit and also about the architecture of the Metasploit framework.

Resources for Article:


Further resources on this subject:


Mastering Metasploit Write and implement sophisticated attack vectors in Metasploit using a completely hands-on approach with this book and ebook
Published: May 2014
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Nipun Jaswal

Nipun Jaswal is an independent information security specialist with a keen interest in the fields of penetration testing, vulnerability assessments, wireless penetration testing, forensics, and web application penetration testing. He is an MTech in Computer Science from Lovely Professional University, India, and is certified with C|EH and OSWP. While he was at the university, he was the student ambassador of EC-COUNCIL and worked with many security organizations along with his studies. He has a proven track record in IT security training and has trained over 10,000 students and over 2,000 professionals in India and Africa. He is a professional speaker and has spoken at various national and international IT security conferences. His articles are published in many security magazines, such as Hakin9, eforensics, and so on. He is also the developer of a web application penetration testing course for InSecTechs Pvt. Ltd., Hyderabad, India, which is a distance-learning package on testing web applications. He has been acknowledged for finding vulnerabilities in Rapid7, BlackBerry, Facebook, PayPal, Adobe, Kaneva, Barracuda labs, Zynga, Offensive Security, Apple, Microsoft, AT&T, Nokia, Red Hat Linux, CERT-IN, and is also part of the AT&T top 10 security researcher's list for 2013, Q2. Feel free to mail him via mail@nipunjaswal.info or visit his site http://www.nipunjaswal.com for more information.

Books From Packt


 Metasploit Penetration Testing Cookbook, Second Edition
Metasploit Penetration Testing Cookbook, Second Edition

Ruby and MongoDB Web Development Beginner's Guide
Ruby and MongoDB Web Development Beginner's Guide

 Metasploit Penetration Testing Cookbook
Metasploit Penetration Testing Cookbook

Instant RubyMotion App Development [Instant]
Instant RubyMotion App Development [Instant]

 Building Dynamic Web 2.0 Websites with Ruby on Rails
Building Dynamic Web 2.0 Websites with Ruby on Rails

Cloning Internet Applications with Ruby
Cloning Internet Applications with Ruby

Instant Metasploit Starter
Instant Metasploit Starter

 Learning Metasploit Exploitation and Development
Learning Metasploit Exploitation and Development


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software