Mastering Metasploit
上QQ阅读APP看书,第一时间看更新

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.

Note

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 book. 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. We will see the working of print_line in the latter half of this chapter.

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.

Note

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. We will use methods heavily in the latter part of this chapter as well as in the next few chapters.

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:

Decision-making operators

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.

Tip

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.

Tip

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: