Ruby
2 min readArticle
Ruby is a dynamic, interpreted, object-oriented scripting language with elegant syntax. Security professionals care about Ruby primarily because Metasploit Framework is written in Ruby — understanding Ruby lets you write custom modules, modify exploits, and extend Metasploit. Also, Rails (Ruby on Rails) powers many web apps and has had significant CVEs.
Security Relevance
- Metasploit Framework is Ruby — you need Ruby to write modules
- Ruby on Rails has had notable CVEs (mass assignment, SQL injection via YAML deserialization)
- Many security scripts and CTF solutions use Ruby
- Metasploit modules: payloads, exploits, post-exploitation are all Ruby files
Setup
bash
# Install Ruby
sudo apt install ruby ruby-dev
# Check version
ruby --version
# Run a script
ruby script.rb
# Interactive console
irb
# Install gems
gem install metasploit-framework
Basics
ruby
# Variables (no type declaration)
target = "192.168.1.1"
port = 443
is_open = false
# String interpolation
puts "Connecting to #{target}:#{port}"
# Arrays and hashes
ports = [22, 80, 443, 3389, 8080]
services = { 22 => "SSH", 80 => "HTTP", 443 => "HTTPS" }
# Loops
ports.each do |p|
puts "Checking port #{p}: #{services[p] || 'unknown'}"
end
(1..254).each do |i|
puts "192.168.1.#{i}"
end
Writing a Metasploit Module (Template)
ruby
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
include Msf::Exploit::Remote::Tcp
def initialize(info = {})
super(update_info(info,
'Name' => 'My Custom Exploit',
'Description' => 'Exploits a vulnerability in target service',
'Author' => ['Your Name'],
'License' => MSF_LICENSE,
'Platform' => 'linux',
'Targets' => [['Auto', {}]],
'DefaultTarget' => 0
))
register_options([
Opt::RPORT(9999)
])
end
def exploit
connect
buf = 'A' * 100 # Overflow buffer
sock.put(buf)
handler
disconnect
end
end
Networking in Ruby
ruby
require 'socket'
# TCP connect check (port scanner)
def port_open?(host, port, timeout=1)
begin
Timeout::timeout(timeout) do
s = TCPSocket.new(host, port)
s.close
true
end
rescue
false
end
end
[22, 80, 443, 3389].each do |port|
status = port_open?("192.168.1.1", port) ? "OPEN" : "closed"
puts "#{port}: #{status}"
end
File Operations
ruby
# Read wordlist and attack
File.readlines('wordlist.txt').each do |line|
password = line.chomp
# attempt login...
end
# Write results
File.open('results.txt', 'a') do |f|
f.puts "Found: #{user}:#{pass}"
end
Useful Gems for Security
bash
gem install net-ssh # SSH connections
gem install mechanize # Web scraping / form automation
gem install nokogiri # HTML/XML parsing
gem install httparty # HTTP requests
Metasploit Module Locations
bash
# Custom modules go here
~/.msf4/modules/exploits/
~/.msf4/modules/post/
~/.msf4/modules/auxiliary/
# Reload in msfconsole
msf> reload_all
See Also
- bash-scripting-guide - For simpler scripting tasks
- python-programming-guide - Alternative scripting language
techzonesite.comUnlock Your IT Potential