Questions about this topic? Sign up to ask in the talk tab.

Difference between revisions of "Ruby"

From NetSec
Jump to: navigation, search
(ruby cli)
(Massive rewrite)
Line 1: Line 1:
Ruby is one of many [[interpreted languages]] written in [[C]] used in [[Linux]] systems for command line tools and serving [[web applications]]. [[Ruby on Rails]] is an object-oriented MVC framework written in [[ruby]] served by WEBRICK and mongrel on [[Linux]] systems.
+
=Ruby=
 +
 
 +
[http://www.ruby-lang.org Ruby] is an interpreted, dynamically typed, reflective, semi-Functional and Object Orientated scripting language. Ruby is said to be semi-Functional because it supports hire-order functions (aka lambdas) and closures (aka blocks). Ruby was created by [http://en.wikipedia.org/wiki/Yukihiro_Matsumoto Yukihiro "Matz" Matsumoto] and was first released in 1995. Matz's goal was to combine powerful features from various other programming languages, and create a programming language maximized for developer happiness; as opposed to computational efficiency. Ruby's Object Model mirrors that of Smalltalk, the syntax shares some similarities with Bash, Perl, Python, and the scoping rules for closures was taken from LISP.
 +
 
 
{{immediate|content}}
 
{{immediate|content}}
  
=Development Environment=
+
==Key Differences==
==ruby cli==
+
 
Type irb at the commandline to use the default interpreter. If you have rubinius, an interpreter optimized for performance similar to how the sbcl or pypy interpreters are, its rbx. If you want to have autocompletion and a nicer interface, installing the pry interpreter gem through your package manager or through rubygems is a good idea.
+
In Ruby <i>everything</i> is an Object, even primitives such as Integers and Strings are Objects. Thus, you can call methods on primitives:
* It can be helpful to use the '''-c''' option to perform a syntax check:
+
 
{{LinuxCMD|ruby -c test.rb
+
<pre>
 +
0x42.chr
 +
# => "A"
 +
 
 +
"hello".reverse
 +
# => "olleh"
 +
 
 +
1.5.round
 +
# => 2</pre>
 +
 
 +
Since everything in Ruby is an Object, every statement has a return value; there is no void in Ruby:
 +
 
 +
<pre>
 +
result = if x > 10
 +
          "high"
 +
        else
 +
          "low"
 +
        end</pre>
 +
 
 +
Ruby does have the concept of null, which is the <kbd>nil</kbd> Object.
 +
 
 +
Of course, every Object is created from a Class. Ruby allows you to introspect (or reflect) Objects and Classes:
 +
 
 +
<pre>
 +
0x42.class
 +
# => Fixnum
 +
 
 +
Fixnum.ancestors
 +
# => [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]
 +
 
 +
0x42.methods
 +
# => [:to_s, :-@, :+, :-, :*, :/, :div, :%, :modulo, :divmod, :fdiv, :**, :abs, :magnitude, :==, :===, :<=>, :>, :>=, :<, :<=, :~, :&, :|, :^, :[], :<<, :>>, :to_f, :size, :zero?, :odd?, :even?, :succ, :integer?, :upto, :downto, :times, :next, :pred, :chr, :ord, :to_i, :to_int, :floor, :ceil, :truncate, :round, :gcd, :lcm, :gcdlcm, :numerator, :denominator, :to_r, :rationalize, :singleton_method_added, :coerce, :i, :+@, :eql?, :quo, :remainder, :real?, :nonzero?, :step, :to_c, :real, :imaginary, :imag, :abs2, :arg, :angle, :phase, :rectangular, :rect, :polar, :conjugate, :conj, :between?, :nil?, :=~, :!~, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
 +
</pre>
 +
 
 +
Ruby also supports anonymous functions, aka closures or blocks. Closures allow you to pass a block of code to a function as an Object, which the function can then call back to. One good example of this is the <kbd>Integer#times</kbd> method, which simply calls a block of code n-times:
 +
 
 +
<pre>
 +
10.times { puts "haha I'm using blocks!" }
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
# haha I'm using blocks!
 +
</pre>
 +
 
 +
Since every statement has a return value, and blocks are just groupings of statements, we can use them to transform data:
 +
 
 +
<pre>(1..10).map { |i| i * 2 }
 +
# => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
 +
 
 +
["racecar", "dog", "radar", "cat"].select { |word| word == word.reverse }
 +
# => ["racecar", "radar"]</pre>
 +
 
 +
==Getting Started==
 +
 
 +
All Linux distributions provide packages for Ruby, and other Ruby development tools:
 +
 
 +
Debian / Ubuntu:
 +
 
 +
<pre>sudo apt-get install ruby1.9.1-full</pre>
 +
 
 +
RedHat / Fedora:
 +
 
 +
<pre>sudo apt-get install ruby ruby-dev irb rubygems</code>
 +
 
 +
Mac OS X systems ship with an older version of Ruby already installed, however you will want to use the latest version (current 1.9.3). The easiest way to install Ruby on a *nix platform, which does not provide an recent version of Ruby, is with the [https://rvm.io/ Ruby Version Manager (RVM)]. RVM is a set of bash scripts which can download, compile, install and update Ruby all within one's home directory.
 +
 
 +
<pre>curl -L https://get.rvm.io | bash -s stable --ruby</pre>
 +
 
 +
==Learning==
 +
 
 +
There are free ebooks and websites which teach you how to program in Ruby:
 +
 
 +
* [http://tryruby.org/ TryRuby] in your browser!
 +
* [http://www.humblelittlerubybook.com/ The Humble Little Ruby Book]
 +
* [http://ruby-doc.org/docs/ProgrammingRuby/ Programming in Ruby (1.8): The Pragmatic Programmer's Guide]
 +
* [http://ruby.bastardsbook.com/ The Bastards Book of Ruby]
 +
* [http://rubylearning.com/ Learning Ruby] (blog)
  
 +
Of course, there are many other commercial books and websites on Ruby:
  
Syntax OK}}
+
* [http://www.amazon.com/gp/product/1934356085/ref=as_li_tf_tl?ie=UTF8&tag=redditrrubyco-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1934356085 Programming Ruby 1.9: The Pragmatic Programmers’ Guide]
* For larger projects:
+
* [http://www.amazon.com/gp/product/0596516177/ref=as_li_tf_tl?ie=UTF8&tag=redditrrubyco-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0596516177 The Ruby Programming Language]
{{LinuxCMD|find -name \*.rb -exec ruby -c '{}' \;
+
* [http://www.amazon.com/gp/product/1933988657/ref=as_li_qf_sp_asin_tl?ie=UTF8&tag=redditrrubyco-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1933988657 Well Grounded Rubyist]
 +
* [http://www.amazon.com/gp/product/0321584104/ref=as_li_tf_tl?ie=UTF8&tag=redditrrubyco-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321584104 Eloquent Ruby]
 +
* [https://cooperpress.com/rubyreloaded Ruby Reloaded (online course)]
 +
* [https://rubyoffrails.com/ Ruby Off Rails (online course)]
  
 +
==Alternate Implementations==
  
Syntax OK
+
The primary implementation of Ruby is known as MRI (Matz Ruby Implementation) or CRuby. However, like any other programming language, Ruby also has many alternate implementations.
  
Syntax OK
+
* [http://jruby.org/ JRuby]: Ruby implemented on the Java Virtual Machine (JVM). It may be slow to startup, but once running JRuby is extremely performant. Consider using JRuby for highly parallized/threaded programs.
 +
* [http://rubini.us Rubinius]: Ruby implemented on [http://llvm.org/ LLVM]. Rubinius has a small core of C++ that uses LLVM to interpret, compile and run Ruby code. The majority of Rubinius is actually written in Ruby, which makes the source-code extremely readable.
 +
* [http://www.ironruby.net/ IronRuby]: Ruby implemented ontop of the Microsoft .NET Dynamic Language Runtime (DLR).
 +
* [https://github.com/mruby/mruby/ MRuby]: A custom C implementation of Ruby, designed for embedded systems. MRuby seeks to compete with Lua.
  
./vm.rb:36: syntax error, unexpected keyword_defined, expecting '('
+
==Development Tools==
  
:return nil if @state > 0 &#x7c;&#x7c; not defined? @machine_name
+
<kbd>irb</kbd> is the Ruby interactive console, similar to <kbd>python</kbd> or <kbd>perlconsole</kbd>. IRB also supports tab-completion, which can be enabled by adding <kbd>require 'irb/completion'</kbd> to your <kbd>~/.irbrc1</kbd> file.
  
...
+
<pre>$ irb
}}
+
>> RUBY_VERSION
 +
=> "1.9.3"</pre>
  
==irb==
+
<kbd>gem</kbd>, or better known as RubyGems, is the package manager for Ruby. RubyGems allows you to install Ruby libraries, or Gems, from [https://rubygems.org/ RubyGems.org]. Installed Gems can be loaded with the <kbd>require</kbd> method:
==gem==
+
  
=Your first application=
+
<pre>$ gem install foo-bar
=Variables and data types=
+
$ irb
=Boolean Logic=
+
>> require 'foo/bar'
=Loops=
+
=> true</pre>
=User Input=
+
=User-Defined Functions=
+
=Security=
+
=Examples of Useful Programs=
+
Many times a hacker has stopped to ask how a character is represented in ascii, possibly for alphanumeric shellcode. Rather than having to resort to wikipedia, why not throw together a script? We'll call it asciispeek.rb
+
  
<source lang="ruby">
+
<kbd>ri</kbd> is a Ruby Documentation indexing tool. RI allows you to quickly looking documentation for Ruby methods, from the command line:
  
#!/usr/bin/ruby
+
<pre>$ ri Array#pack</pre>
  
def asciispeek(x)
+
<kbd>rake</kbd> is like Make, but for Ruby. Rake is used by Ruby projects to automate various tasks, such as testing, building or installing the project.
      x.each_byte do |c|
+
    puts c.to_s(2)
+
end
+
end
+
  
asciispeek(ARGV.join(' ').to_s)
+
<pre>$ rake build</pre>
  
</source>
+
[http://gembundler.com/ Bundler] is a RubyGem that allows projects to lock-down their dependencies. Bundler is commonly used by developers to automatically install dependencies for a project (<kbd>bundle install</kbd>) or to generate new projects (<kbd>bundle gem foo</kbd>).
  
This script takes the arguments from the shell (ARGV) and joins them into one string. The act of joining removes the whitespace between them, so we add it back in, and then convert it to a string. The result is then passed to our function. Our function calls an enumerable method of the string class, each_byte, which gets at the byte representation of the character. We then pipe it into a block which converts it into a base 2 number and then prints it. A simple edit could make this spit out the hex representation, or the octal. This is a good example of the idea of reusing code. By encapsulating the actual actions into a function, we can copy this function into a class or script that we make in the future.
+
==Useful Libraries==
  
[[Category:Programming Languages]]
+
* [http://nokogiri.org/ Nokogiri]: Fast XML/HTML parser built ontop of libxml. Supports XPath and CSS-path searching of documents.
 +
* [http://sinatrarb.org/ Sinatra]: A minimal library for creating web-apps.
 +
* [https://github.com/ffi/ffi#readme FFI]: Foreign Function Interface for Ruby. Allows you to write bindings to C libraries, entirely in Ruby.
 +
* [http://metafuzz.rubyforge.org/binstruct/ BinStruct]: Binary Structures.
 +
* [https://github.com/hammackj/rex REX]: Various Exploitation helper methods, extracted from Metasploit.
 +
* [https://github.com/emonti/rbkb Ruby BlackBag (rbkb)]: Ruby BlackBag. Misc ruby-based pen-testing/reversing tools. Inspired by Matasano BlackBag.
 +
* [http://ronin-ruby.github.com/ Ronin]: A Ruby platform for vulnerability research and exploit development. Ronin allows for the rapid development and distribution of code, Exploits, Payloads, Scanners, etc, via Repositories. Provides a customized Ruby Console, built-in Database and many useful classes, modules, methods, libraries.
 +
* [https://github.com/sophsec/ruby-nmap#readme ruby-nmap]: Automate nmap from Ruby.
 +
* [https://github.com/sophsec/ffi-udis86#readme ffi-udis86]: Ruby FFI bindings to the [http://udis86.sourceforge.net/ udis86] dissassembler.
  
{{programming}}{{social}}
+
==Community==
  
[[Category:Interpreted languages]]
+
* [irc://irc.freenode.net/#ruby #ruby on irc.freenode.net]
 +
* [http://reddit.com/r/ruby /r/ruby]
 +
* [https://github.com/ GitHub]: where the majority of Ruby projects are hosted and developers collaborate.
 +
* [https://rubygems.org RubyGems.org]: repository for all Ruby libraries)
 +
* [http://rubydoc.info/ RubyDoc]: Hosts documentation for Ruby [http://rubydoc.info/stdlib/core core], [http://rubydoc.info/stdlib/ stdlib] and all [http://rubydoc.info/gems/ RubyGems].

Revision as of 11:52, 12 August 2012

Ruby

Ruby is an interpreted, dynamically typed, reflective, semi-Functional and Object Orientated scripting language. Ruby is said to be semi-Functional because it supports hire-order functions (aka lambdas) and closures (aka blocks). Ruby was created by Yukihiro "Matz" Matsumoto and was first released in 1995. Matz's goal was to combine powerful features from various other programming languages, and create a programming language maximized for developer happiness; as opposed to computational efficiency. Ruby's Object Model mirrors that of Smalltalk, the syntax shares some similarities with Bash, Perl, Python, and the scoping rules for closures was taken from LISP.

RPU0j.png This article needs immediate attention, and is in desperate need of content.

Key Differences

In Ruby everything is an Object, even primitives such as Integers and Strings are Objects. Thus, you can call methods on primitives:

0x42.chr
# => "A"

"hello".reverse
# => "olleh"

1.5.round
# => 2

Since everything in Ruby is an Object, every statement has a return value; there is no void in Ruby:

result = if x > 10
           "high"
         else
           "low"
         end

Ruby does have the concept of null, which is the nil Object.

Of course, every Object is created from a Class. Ruby allows you to introspect (or reflect) Objects and Classes:

0x42.class
# => Fixnum

Fixnum.ancestors
# => [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]

0x42.methods
# => [:to_s, :-@, :+, :-, :*, :/, :div, :%, :modulo, :divmod, :fdiv, :**, :abs, :magnitude, :==, :===, :<=>, :>, :>=, :<, :<=, :~, :&, :|, :^, :[], :<<, :>>, :to_f, :size, :zero?, :odd?, :even?, :succ, :integer?, :upto, :downto, :times, :next, :pred, :chr, :ord, :to_i, :to_int, :floor, :ceil, :truncate, :round, :gcd, :lcm, :gcdlcm, :numerator, :denominator, :to_r, :rationalize, :singleton_method_added, :coerce, :i, :+@, :eql?, :quo, :remainder, :real?, :nonzero?, :step, :to_c, :real, :imaginary, :imag, :abs2, :arg, :angle, :phase, :rectangular, :rect, :polar, :conjugate, :conj, :between?, :nil?, :=~, :!~, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]

Ruby also supports anonymous functions, aka closures or blocks. Closures allow you to pass a block of code to a function as an Object, which the function can then call back to. One good example of this is the Integer#times method, which simply calls a block of code n-times:

10.times { puts "haha I'm using blocks!" }
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!
# haha I'm using blocks!

Since every statement has a return value, and blocks are just groupings of statements, we can use them to transform data:

(1..10).map { |i| i * 2 }
# => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

["racecar", "dog", "radar", "cat"].select { |word| word == word.reverse }
# => ["racecar", "radar"]

Getting Started

All Linux distributions provide packages for Ruby, and other Ruby development tools:

Debian / Ubuntu:

sudo apt-get install ruby1.9.1-full

RedHat / Fedora:

sudo apt-get install ruby ruby-dev irb rubygems</code>

Mac OS X systems ship with an older version of Ruby already installed, however you will want to use the latest version (current 1.9.3). The easiest way to install Ruby on a *nix platform, which does not provide an recent version of Ruby, is with the [https://rvm.io/ Ruby Version Manager (RVM)]. RVM is a set of bash scripts which can download, compile, install and update Ruby all within one's home directory.

<pre>curl -L https://get.rvm.io | bash -s stable --ruby

Learning

There are free ebooks and websites which teach you how to program in Ruby:

Of course, there are many other commercial books and websites on Ruby:

Alternate Implementations

The primary implementation of Ruby is known as MRI (Matz Ruby Implementation) or CRuby. However, like any other programming language, Ruby also has many alternate implementations.

  • JRuby: Ruby implemented on the Java Virtual Machine (JVM). It may be slow to startup, but once running JRuby is extremely performant. Consider using JRuby for highly parallized/threaded programs.
  • Rubinius: Ruby implemented on LLVM. Rubinius has a small core of C++ that uses LLVM to interpret, compile and run Ruby code. The majority of Rubinius is actually written in Ruby, which makes the source-code extremely readable.
  • IronRuby: Ruby implemented ontop of the Microsoft .NET Dynamic Language Runtime (DLR).
  • MRuby: A custom C implementation of Ruby, designed for embedded systems. MRuby seeks to compete with Lua.

Development Tools

irb is the Ruby interactive console, similar to python or perlconsole. IRB also supports tab-completion, which can be enabled by adding require 'irb/completion' to your ~/.irbrc1 file.

$ irb
>> RUBY_VERSION
=> "1.9.3"

gem, or better known as RubyGems, is the package manager for Ruby. RubyGems allows you to install Ruby libraries, or Gems, from RubyGems.org. Installed Gems can be loaded with the require method:

$ gem install foo-bar
$ irb
>> require 'foo/bar'
=> true

ri is a Ruby Documentation indexing tool. RI allows you to quickly looking documentation for Ruby methods, from the command line:

$ ri Array#pack

rake is like Make, but for Ruby. Rake is used by Ruby projects to automate various tasks, such as testing, building or installing the project.

$ rake build

Bundler is a RubyGem that allows projects to lock-down their dependencies. Bundler is commonly used by developers to automatically install dependencies for a project (bundle install) or to generate new projects (bundle gem foo).

Useful Libraries

  • Nokogiri: Fast XML/HTML parser built ontop of libxml. Supports XPath and CSS-path searching of documents.
  • Sinatra: A minimal library for creating web-apps.
  • FFI: Foreign Function Interface for Ruby. Allows you to write bindings to C libraries, entirely in Ruby.
  • BinStruct: Binary Structures.
  • REX: Various Exploitation helper methods, extracted from Metasploit.
  • Ruby BlackBag (rbkb): Ruby BlackBag. Misc ruby-based pen-testing/reversing tools. Inspired by Matasano BlackBag.
  • Ronin: A Ruby platform for vulnerability research and exploit development. Ronin allows for the rapid development and distribution of code, Exploits, Payloads, Scanners, etc, via Repositories. Provides a customized Ruby Console, built-in Database and many useful classes, modules, methods, libraries.
  • ruby-nmap: Automate nmap from Ruby.
  • ffi-udis86: Ruby FFI bindings to the udis86 dissassembler.

Community