Tuesday, May 29, 2012

Saving Fiddler Sessions on Exit

By Neelay Shah.

If you are like me and love to use Fiddler frequently, it can be incredibly frustrating at times when you close Fiddler by mistake or in a hurry and all your work is lost since Fiddler does not prompt (or autosave) you to save the sessions before closing. Now the great thing about Fiddler is that it is extremely extensible and so I customized the existing Fiddler rules so that the user is prompted to save the session when Fiddler is closed.

Before we get into the details of the customized rule let’s spend a few minutes understanding how Fiddler’s “Load Archive” and “Save” features work –

  1. Fiddler does not have an “auto save” feature and as such if you do not explicitly save the session(s) then your session(s) are lost as soon as Fiddler is closed.
  2. The “Save” functionality saves the captured sessions as a snapshot in time. So, if you explicitly save a Fiddler session, continue browsing the web application (being proxy'ed through Fiddler) and then exit Fiddler (without saving) all the new sessions that were captured after the previous “Save” operation are lost.
  3. The “Load Archive” functionality loads and appends the user selected session archive to the already open and existing capture. Now if the “Save” operation is invoked then the current capture plus the existing session archive (that was loaded) is saved as a new session archive.

Now let’s look at the rule modifications that will cause Fiddler to allow the user to save sessions when Fiddler is closed. I have tested this with Fiddler v2.3.9.3. I recommend installing the Syntax Highlighting extension - http://fiddler2.com/redir/?id=SYNTAXVIEWINSTALL before attempting to modify the FiddlerScript Rules. Once you install the Syntax Highlighting extension, launch Fiddler and you should see a new tab “FiddlerScript” (between the Composer and the Filters tab). Click the “FiddlerScript” tab and that should open the Rules file. Then you can add the following code appropriately and click “Save Script”.

You will most likely already have an OnShutdown() function in which case simply add the following code to the beginning of the OnShutdown() function

 static function OnShutdown() {  
      // MessageBox.Show("Fiddler has shutdown");  
      var exitPromptResult: DialogResult;  
      exitPromptResult = MessageBox.Show("Do you want to save this session before Fiddler exits?", "Save on Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);  
      if (DialogResult.Yes != exitPromptResult)  
           //The user does not want to save the capture so proceed to exit  
      //The user selected Yes - Allow the user to save the capture  

Once you add this code and save the Script Rules, the rule will be in effect and Fiddler will start using the same. Now when you close Fiddler, it should prompt you to save the capture. The behavior of this “Save on Exit” prompt is as follows -

  • If you select “No” then the capture will not be saved and Fiddler will exit
  • If you select “Yes” however select “Cancel” on the ensuing “Save Session Archive to…” dialog then the capture will not be saved and Fiddler will exit
  • If you select “Yes” and enter an appropriate archive name and select “Save” on the ensuing “Save Session Archive to…” dialog then the capture will be saved to the appropriate archive.

Monday, May 21, 2012

Am I pwn3d? Windows *Native* Tool Triage

By Tony Lee and Jerry Pierce.

So, you are surfing the web, checking your email, and performing other daily tasks… $#@!, you just realized you clicked a link, opened an attachment, or visited a site that you probably should not have. So what do you do? Cry a little or take action?

Perhaps a friend, family member or neighbor approaches you and asks you to help them “fix their computer” or they say, “I think I have been hacked!”

Whatever the scenario, we have outlined some steps--using native Windows binaries--that you can follow in order to do a little preliminary analysis to detect potential compromise and triage the system.

Indicators of Compromise Covered

  • Processes
  • Network Connections
  • Common File Locations
    • System32
    • Home Directory
  • Persistence Mechanisms
    • Services
    • Registry
    • Tasks
    • Startup Directory

If your relative/friend or family member is remote, you will most likely have to send the output to a file or have them read it to you (good luck with that if they aren’t technical), but it is a start.

Note: If you cannot coach family members to get to the cmd prompt--all hope may already be lost ;)

Examine Processes

The following command has been natively present in Windows since XP and 2003. It will list the process name, process ID (PID), and other information.

tasklist >> output.txt

Sample Output

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
System Idle Process            0 Console                 0         16 K
System                         4 Console                 0        212 K
smss.exe                     604 Console                 0        404 K
csrss.exe                    652 Console                 0      1,996 K
winlogon.exe                 676 Console                 0      3,468 K
services.exe                 720 Console                 0      3,368 K
lsass.exe                    732 Console                 0      5,972 K
svchost.exe                  892 Console                 0      4,764 K
svchost.exe                  960 Console                 0      4,164 K
svchost.exe                 1072 Console                 0     19,276 K
svchost.exe                 1132 Console                 0      3,484 K
svchost.exe                 1272 Console                 0      3,064 K
explorer.exe                1408 Console                 0     15,252 K
VMwareUser.exe              1648 Console                 0      2,888 K
ctfmon.exe                  1660 Console                 0      3,004 K
wracing.exe                 1680 Console                 0      1,220 K
sqlmangr.exe                1692 Console                 0      4,804 K
svchost.exe                 1808 Console                 0      3,700 K
inetinfo.exe                1864 Console                 0      7,904 K
sqlservr.exe                1880 Console                 0      7,768 K
VMwareService.exe            128 Console                 0      2,236 K
alg.exe                     1168 Console                 0      3,536 K
cmd.exe                     1928 Console                 0      2,836 K
defrag.exe                  1396 Console                 0      3,304 K
dfrgntfs.exe                1260 Console                 0      9,556 K
wmiprvse.exe                1756 Console                 0      5,876 K
firefox.exe                  380 Console                 0     24,852 K
tasklist.exe                1284 Console                 0      4,312 K

Once the command has been executed a well trained eye can usually spot an oddly named program that is running, however some malware will try to appear as innocuous as possible and won’t stand out from a process name alone. If something is unfamiliar, there are many sites that can be used to investigate a binary name such as http://www.processlibrary.com/. (No results from processlibrary.com can be as concerning as a positive bad hit).

ProcessLibrary.com Example

Search results for: wracing.exe Your search "wracing.exe" did not match any documents. Make sure the search term was spelled correctly.

Examine Network Connections

The following command has been natively present in Windows for ages, however the -o option has been available since at least Windows XP and 2003. The -o option provides the PID of the process that is holding the port open. This PID can be cross referenced with the process information that you pulled in the previous section to examine the process name that is holding the port open.

netstat -ano >> output.txt

Sample Output

C:\>netstat -ano

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP                 LISTENING       1864
  TCP                 LISTENING       1864
  TCP                LISTENING       960
  TCP                LISTENING       1864
  TCP                LISTENING       4
  TCP               LISTENING       1864
  TCP              LISTENING       1168
  TCP         ESTABLISHED     380
  TCP         ESTABLISHED     380
  TCP         ESTABLISHED     380
  TCP         ESTABLISHED     380
  TCP              LISTENING       4
  TCP       ESTABLISHED     380
  TCP       ESTABLISHED     380
  TCP        ESTABLISHED     380
  TCP        ESTABLISHED     380
  TCP        ESTABLISHED     380
  TCP       ESTABLISHED     1680
  UDP            *:*                                    4
  UDP            *:*                                    732
  UDP           *:*                                    1864
  UDP           *:*                                    732
  UDP          *:*                                    1072
  UDP     *:*                                    1072
  UDP     *:*                                    4
  UDP     *:*                                    

You are looking for any “odd” port that is listening as this might indicate the malware has placed a backdoor onto your system, or any connections to odd sites/locations around the world which you haven’t initiated.

We realize that netstat -anb can provide even more information to include the libraries that are associated with the PID, however this takes longer to run and may not be allowed to run without elevating the prompt in Windows 7.

Examine Common File Locations

The following command has been natively present in Windows since the dawn of time, however the options may not be well known to you or your family members. Running the “dir” command with the following syntax will produce a listing that is sorted by the file creation time.


Many files are located here and thus this is a common place for malware to hide among the weeds

dir /o:d /t:c c:\windows\system32 >> output.txt

Sample Output

C:\>dir /o:d /t:c c:\windows\system32
01/07/2010  05:48 PM           689,152 xpsp3res.dll
01/07/2010  06:02 PM    <DIR>          en
01/07/2010  06:02 PM    <DIR>          scripting
01/07/2010  06:02 PM    <DIR>          en-us
01/07/2010  06:19 PM         1,676,288 xpssvcs.dll
01/07/2010  06:19 PM           575,488 xpsshhdr.dll
01/07/2010  06:19 PM           117,760 prntvpt.dll
01/07/2010  06:20 PM    <DIR>          XPSViewer
01/07/2010  06:34 PM             2,560 xpsp4res.dll
01/07/2010  07:39 PM        25,966,024 MRT.exe
01/07/2010  07:50 PM             3,706 TZLog.log
            2009 File(s)    408,261,849 bytes
              52 Dir(s)   2,505,060,352 bytes free

User’s home directory

This is a popular spot for malware to hide because the attacker has permission to write to these locations under the context of the user.

dir /a /s /o:d /t:c “%USERPROFILE%” >> output.txt

Sample Output

dir /a /s /o:d /t:c "%USERPROFILE%"

 Directory of C:\Documents and Settings\Administrator\Local Settings\Temp
01/07/2010  07:00 PM            54,272 Set29F.tmp
01/07/2010  07:42 PM    <DIR>          NDP1.1sp1-KB953297-X86
01/07/2010  07:47 PM            14,010 ASPNETSetup_00002.log
09/13/2010  09:24 PM             8,141 lick_me.jpg
09/13/2010  09:24 PM            37,376 wracing.exe
09/13/2010  09:24 PM            28,160 wracing.dll
09/13/2010  09:28 PM    <DIR>          plugtmp
03/23/2012  01:43 PM    <DIR>          VMwareDnD
03/23/2012  02:54 PM               104 pdracing.tmp

The filenames above are from real malware--we did not make those up.

Investigating Persistence

Sometimes the persistence mechanism (the way malware tries to assure its continued existence on a system) can give away the presence of malicious software on a system. The following persistence mechanisms will be examined:

  • Services
  • Registry
  • Scheduled Tasks
  • Startup Directory

Examine Services

The following command has been natively present in Windows since before the dawn of time. This command is commonly used to list the started services.

net start >> output.txt

Sample Output
C:\>net start
These Windows services are started:

   Application Layer Gateway Service
   Automatic Updates
   COM+ Event System
   Computer Browser
   Cryptographic Services
   DCOM Server Process Launcher
   DHCP Client
   Distributed Link Tracking Client
   DNS Client
   Event Log
   FTP Publishing
   Help and Support
   IIS Admin
   IPSEC Services
   Logical Disk Manager
   Network Connections
   Network Location Awareness (NLA)
   Plug and Play
   Protected Storage
   Remote Access Connection Manager
   Remote Procedure Call (RPC)
   Remote Registry
   Secondary Logon
   Security Accounts Manager
   Security Center
   Shell Hardware Detection
   System Event Notification
   Task Scheduler
   TCP/IP NetBIOS Helper
   Terminal Services
   VMware Tools Service
   Windows Firewall/Internet Connection Sharing (ICS)
   Windows Management Instrumentation
   Windows Time
   World Wide Web Publishing

The command completed successfully.

The following command has been natively present in Windows since XP and 2003. It will list the process name, process ID (PID), and the keyname for the service.

tasklist /svc >> output.txt

Sample Output
C:\>tasklist /svc

Image Name                   PID Services
========================= ====== ============================================
System Idle Process            0 N/A
System                         4 N/A
smss.exe                     604 N/A
csrss.exe                    652 N/A
winlogon.exe                 676 N/A
services.exe                 720 Eventlog, PlugPlay
lsass.exe                    732 PolicyAgent, ProtectedStorage, SamSs
svchost.exe                  892 DcomLaunch, TermService
svchost.exe                  960 RpcSs
svchost.exe                 1072 Browser, CryptSvc, Dhcp, dmserver,
                                 EventSystem, helpsvc, lanmanserver,
                                 lanmanworkstation, Netman, Nla, RasMan,
                                 Schedule, seclogon, SENS, SharedAccess,
                                 ShellHWDetection, TapiSrv, TrkWks, W32Time,
                                 winmgmt, wscsvc, wuauserv
svchost.exe                 1132 Dnscache
svchost.exe                 1272 LmHosts, RemoteRegistry
explorer.exe                1408 N/A
VMwareUser.exe              1648 N/A
ctfmon.exe                  1660 N/A
wracing.exe                 1680 N/A
sqlmangr.exe                1692 N/A
svchost.exe                 1808 WebClient
inetinfo.exe                1864 IISADMIN, MSFtpsvc, W3SVC
sqlservr.exe                1880 MSSQLSERVER
VMwareService.exe            128 VMTools
alg.exe                     1168 ALG
cmd.exe                     1928 N/A
firefox.exe                  380 N/A
notepad.exe                 1344 N/A
tasklist.exe                1820 N/A
wmiprvse.exe                1892 N/A

Additional analysis could include digging further into a particular service shown above. A great native tool for this is sc (service control):

sc qc  >> output.txt

Sample Output
C:\>sc qc webclient
[SC] GetServiceConfig SUCCESS

SERVICE_NAME: webclient
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\WINDOWS\System32\svchost.exe -k LocalService
        LOAD_ORDER_GROUP   : NetworkProvider
        TAG                : 0
        DISPLAY_NAME       : WebClient
        DEPENDENCIES       : MRxDAV

Examine Registry Entries

The following command has been natively present in Windows for quite some time--however, the keys are the ones examined by Sysinternal’s autoruns:

reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
reg query "HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"
reg query "HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components"
reg query "HKLM\SOFTWARE\Wow6432Node\Microsoft\Active Setup\Installed Components"
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"

Sample Output
C:\>reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"


    ctfmon.exe  REG_SZ  C:\WINDOWS\system32\ctfmon.exe
    wracing     REG_SZ  C:\Documents and Settings\Administrator\Local Settings\Temp\wracing.exe -installkys

With this sample output, we see that “wracing.exe” is in the “C:\Documents and Settings\Administrator\Local Settings\Temp” directory. We suggest you review the file listing of this directory, sorted by file creation time as well to see what other artifacts may be present from the same timeframe.

Examine Scheduled Tasks

The following command has been natively present in Windows for quite a while, however it is falling out of favor in Windows 7 and 2008:

at >> output.txt

Sample Output
There are no entries in the list.

Windows 7 and 2008 prefers the following newer command:

schtasks >> output.txt

Sample Output

C:\Documents and Settings\Administrator>schtasks

TaskName                            Next Run Time          Status
=================================== ====================== ===============
Ezyme                               16:33:00, 3/23/2012

Examine Startup Directory

We will use the ‘dir’ command again in order to inspect the startup directory specifically:

dir “C:\Documents and Settings\All Users\Start Menu\Programs\Startup”
dir “C:\Documents and Settings\\Start Menu\Programs\Startup”
dir "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"

Sample Output
C:\>dir "c:\documents and settings\Administrator\start menu\programs\startup"
 Volume in drive C has no label.
 Volume Serial Number is 442E-ACB9

 Directory of c:\documents and settings\Administrator\start menu\programs\startup

11/15/2006  01:37 PM    <DIR>          .
11/15/2006  01:37 PM    <DIR>          ..
11/15/2006  01:37 PM               607 putbginfo.bat.lnk
               1 File(s)            607 bytes
               2 Dir(s)   2,503,716,864 bytes free

Initial Analysis of the Results

Analysis often takes far longer than the time required to run the commands. However, according to the sample information above, it appears that we have at least two infections on this host. The data below ties everything together.

Malicious software is present in the process list here:

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
wracing.exe                 1680 Console                 0      1,220 K

It also has a connection out to a known bad site:

  TCP       ESTABLISHED     1680

Malicious files are present in the following directory:

C:\Documents and Settings\Administrator\Local Settings\Temp

09/13/2010  09:24 PM             8,141 lick_me.jpg
09/13/2010  09:24 PM            37,376 wracing.exe
09/13/2010  09:24 PM            28,160 wracing.dll

The persistence mechanism is via the registry:

wracing     REG_SZ  C:\Documents and Settings\Administrator\Local Settings\Temp\wracing.exe -installkys

There is also a second (most likely unrelated) suspicious task that runs via the scheduler:

C:\Documents and Settings\Administrator>schtasks
TaskName                            Next Run Time          Status
=================================== ====================== ===============
Ezyme                               16:33:00, 3/23/2012

Food for Thought

If the infection is using rootkit technology, there is a good chance that the native Windows tools will not show you anything. If nothing shows up as indicators of compromise, but they are still convinced they are owned--look for our next post (Am I P0wn3d? Lesson 102 - Windows *Non-Native* Tool Triage) which leverages non-native tools which may provide more insight into the potential breach. Non-native tools may also pull the same information, without using the traditional Windows APIs which can help discover the present of rootkit technology. Happy hunting!

What Native Tips Do You Have?

Do you have any tips or tricks using Native Windows tools? Share them in the comments below!!!

Thursday, May 17, 2012

Phishing 101 - Subject: Access Blocked

By Jerry Pierce.

Give a man food, and he’ll eat for one day – teach a man to PHISH and he’ll use your credit card to live a lifetime. Well, at least until you notify your bank…

Earlier this week, Brad Antoniewicz came across a piece of spam in his mailbox that caught his attention - it was strangely professional. He offered up the e-mail to anyone in Foundstone who was curious and I choose to dive in!

Taking a look, the email itself looks fairly solid with the exception of the originating email address of “chase@accounts.com” which should start alarm bells ringing:

If you banked with Chase you would be very alarmed at the seeming legitimacy of this email alert!

If you open the “Restore Access Form” which is attached, you get presented with a very official looking interface to what purports to be chaseonline.chase.com:

The primary reason that everything looks so legit is that the hacker is pulling the graphical images from the legitimate “chaseonline.chase.com” site.

Sharp eyed and paranoid users might notice the connection the form opened isn’t using HTTPS and that everything you enter is traversing the internet in clear text. No banking site would consider prompting you for that sort of critical financial information without safeguarding it via HTTPS.

If you “hover” of the “NEXT” button you see that instead of “http://www.chase.com” being displayed we see the true destination of any information you enter:

Hrmm... looks pretty suspicious!

Following up this trail, we start by using one of the online Registries to determine the country and ownership of the IP address in question. Since we don’t know off-hand where that IP resides, we’ll query the American Registry of Internet Numbers or “ARIN” which identifies the IP address as being managed by “RIPE” for EMEA based resolution.

Once there, a “whois” lookup shows that the IP address which is receiving the credit card data is found to be part of a network block allocated to France Telecom:

So while the email looks legit and has a potentially true “ring” to it, always be suspicious and rather than just supplying this sort of information to a nameless site somewhere on the internet, contact your bank or credit card provider directly for confirmation of any problem.

The site is already down, or at least unresponsive, and a quick search for results in this https://www.phishtank.com/phish_detail.php?phish_id=1438995 which identifies it as a phish!

So remember, don't open that attachment or click that link!

Here are a couple phishing references (courtesy of Chris Silvers):

Tuesday, May 15, 2012

Mallory MITM + FIX SSL Decryption

by Paul Ambrosini.

Recently, I was faced with testing a Java-based thick client that communicates using the “Financial Information eXchange”protocol, also known as “FIX”. (The protocol is documented here: http://fixprotocol.org/). FIX is “a messaging standard developed specifically for the real-time electronic exchange of securities transactions”. Most thick clients these days use Web-based services and in doing so use some variant of HTTP (or, if not that, plaintext XML interchange), but FIX is different.

In this post I’ll cover how I approached testing this protocol and the tools I used to test it. I won’t be discussing the FIX protocol in much detail beyond what can be found on the FIX site or various FIX wikis on the net. This post will focus primarily on how to set up and configure Mallory to decrypt the SSL stream from a FIX-speaking thick client.

To start my testing I was given a thick client (the app itself out-of-scope- it’s a developer testing harness). The client was written in Java and had lots of configuration options that later proved useful for testing. This thick client quickly introduced certain limitations to testing, however:
  1. The client itself is out-of-scope, so only findings that apply to the API can be reported;
  2. The thick client is using the FIX protocol over TCP; and
  3. The TCP Stream is SSL encrypted.

I quickly realized that a normal proxy (Fiddler or Burp, for example) was going to be of very limited help. The first suggestion I got was Charles Proxy, which can handle generic TCP/SSL connections. After doing some reading on the FIX API, though, I decided to go with Mallory, since I can write python code to tie in with Mallory and assist my testing.

Information on Mallory can be found here: https://bitbucket.org/IntrepidusGroup/mallory/wiki/Home

The install guide can be found here: https://bitbucket.org/IntrepidusGroup/mallory/wiki/Installation

Note: I originally used the Mallory VM from the torrent; however, at the time of writing, no one was seeding the torrent. For that reason, I based this guide off of a fresh Ubuntu install.

Mallory Initial Setup

I installed Ubuntu 11.04 (Natty Narwhal) Desktop onto a VM with:
  • 3 Network Interface Cards with each set to Bridged
  • 1024 MB of RAM
  • 10 GB of hard disk space
  • A user named “mallory”

Note: These specifications were for the way I was going to setup my network, make sure to decide how you will route traffic in your case.

The first step is getting Mallory installed. We’ll need a shell (for example, xterm,konsole, or gnome-terminal) and internet access to the VM. The network setup for this VM will use one interface as a gateway interface (eth0), one interface as an outgoing interface (eth1) and one interface as a DNS listener (eth2). Upon first boot all three NICs have DHCP and they need to be disabled for internet connectivity.


 $ sudo ifconfig eth0 down  
 $ sudo ifconfig eth2 down  
 $ ping                     #test the connection  

Figure 1: Turning off two interfaces and testing the connection with ping.

Now that the internet connection works we download the Mallory install script and run it.

 $ wget https://bitbucket.org/IntrepidusGroup/mallory/downloads/mallory_install.sh
 $ chmod +x mallory_install.sh
 $ sudo ./mallory_install.sh
 $ sudo ./mallory_install.sh
 **a lot of text later (go grab some tea/coffee)**
 /home/mallory/mallory  #folder to place mallory in
 *hit enter for yes*
 $ cd /home/mallory/mallory/current/src/

Figure 2: Downloading and running the Mallory install script.

Figure 3: Finishing the install script and changing into the new directory.

Once installation is complete and we’re in the Mallory directory, we need to get our network set up correctly.

Routing Traffic

How you use Mallory will be determined by how you route traffic. Mallory can handle all sorts of situations, but for my purposes, setup is fairly simple. I’m going to use my Mallory VM as a network gateway and route traffic from my testing VM through Mallory. Because I am completely controlling my test environment, I don’t need to do any extra ARP poisoning or PPTP setup. This setup has the additional benefit that, once the VM is properly configured, it can easily be “turned on” or “turned off” just by changing a host’s routing tables.

My network setup will use eth0 as the MITM interface and eth2 as the DNS listener interface, so each of these interfaces will need to be up and configured with static IP addresses. eth1 will be the Mallory VM’s connection to the Internet and get a DHCP address. Because we are using Ubuntu we can edit the file /etc/network/interfaces which will persist the settings across reboots.

# First
allow manual interface configuration
$ sudo service network-manager stop
$ sudo killall –w dhclient

Figure 4: Stopping the network manager service and any dhclient processes.

Now open /etc/network/interfaces with your favorite editor. Static IPs on eth0 (MITM) and eth2 (DNS listener) then DHCP on eth1:

$ sudo vi /etc/network/interfaces

Figure 5: Configuration settings for /etc/network/interfaces.

$ sudo ifup eth0
$ sudo ifup eth0
$ sudo ifup eth2
$ ifconfig   # Check the configuration

Figure 6: Turning on the interfaces with "ifup" and checking their settings with "ifconfig".

Install and start dnsmasq on eth2 to act as a DNS request forwarder:

$ sudo apt-get install dnsmasq
$ sudo /etc/init.d/dnsmasq stop
$ sudo /etc/init.d/dnsmasq start -i eth2

Figure 7: Install dnsmasq with apt-get then stop and start the daemon on eth2.

Note: Because we are using Ubuntu, we need to stop the Network Manager service and kill all the dhclient processes. Otherwise, our static addresses will get mysteriously wiped out every few minutes. On a system used for other purposes, this might have adverse consequences.

To make sure everything is working fine, ping and check for connectivity. If you can’t ping out for some reason just do:

$ sudo ifdown eth1
$ sudo killall -w dhclient
$ sudo ifup eth1

…then try to ping again.

Now, because we are controlling the environment, we need to configure our testing VM to route through the gateway. On Windows, configure the IP addressing like so:

Figure 8: Windows network configuration for testing VM

On a Linux system, the following commands produce the same configuration state (commands to kill dhclient and/or network-manager not included):

 $ sudo ifconfig eth0 inet netmask
$ sudo route add default gw
$ echo “nameserver” | sudo tee /etc/resolv.conf

Intercepting Traffic

The next step is to actually start Mallory and confirm that we can capture encrypted traffic. Open two command prompts on the Mallory VM, change to the Mallory directory in each of them, and start Mallory; one in the GUI mode, one in worker mode.

Terminal 1, Worker Mode:

$ cd /home/mallory/mallory/current/src
$sudo python mallory.py

Figure 9: Starting mallory.py for the first time.

Terminal 2, GUI Mode:

$ cd /home/mallory/mallory/current/src
$ sudo python launchgui.py

Figure 10: Executing the launchgui.py script and the GUI started.

After launching the GUI from the command line, the GUI itself should be displayed. Using this interface, configure the interfaces used by Mallory by clicking the checkbox for “Perform MiTM” on the eth0 interface and “Outbound Interface” for the eth1 interface, then click Apply Configuration at the bottom. Terminal 2 – where we launched the GUI – will show some iptables rules get applied.

Figure 11: Start the MiTM and outbound interfaces settings.

In the Protocols tab on the GUI, find the line in Protocol Configuration that looks like:


Mallory uses the semi-colon as the comment character. Since we want to enable capture on this protocol, remove the leading ‘;’ so that the line looks like:


Each line consists of three fields, colon-separated. The first field (“http_1”) is a user-friendly name for the traffic type; we can set this to anything we want. The second field (“http.HTTP”) instructs Mallory how to decode the traffic and correlates to the python code. The third field (“80”) tells Mallory which TCP port it should intercept. Click ‘apply’ to save the changes. You will also see a debug message in Terminal 1 to show HTTP is enabled.

Figure 12: Apply the HTTP protocol MiTM.

For initial testing, only the Interface and Protocol tabs need to be edited. The other tabs will come into play a little later.

To make sure that we’re properly intercepting traffic, switch to the testing VM and open a web browser. Browse to a website normally (such as http://www.google.com) and, if traffic is routing correctly, you should see the images flipped and inverted like in the image below.

Figure 13: www.google.com, with the doodle flipped and inverted by Mallory.

Additionally, every request intercepted by Mallory should generate a DEBUG message in Terminal 1. Look for messages beginning with ‘DEBUG:HTTP’.

Decrypting SSL Traffic

Mallory’s interception of different protocol types is configured by changing the configuration lines in the Protocols tab. First, turn HTTP capture back off by commenting out the line in the protocol configuration tab:


Then configure Mallory to perform SSL Man-in-the-Middle, which is what we need for this application. Uncomment (or add) a line instructing Mallory to intercept SSL communications on port 443:


Click Apply at the bottom. The mallory.py window will print out a debug message reporting that the SSLProtocol module is starting:

Figure 14: Starting SSL MiTM in Mallory.

At the time of writing, the ‘Configured Protocols’ section of the Protocols tab states that SSL Base is not debuggable; this is actually a bug in Mallory. A fix is available, but for our purposes, this is mainly an aesthetic issue. (https://groups.google.com/forum/#!topic/mallory-proxy/PF2MwXOpcEg)

Next, visit Rules tab and locate the “DebugAll”rule. The Rules tab allows the user to choose which messages to show in the Streams tab. Some of the options are server-to-client, client-to-server, both, port etc. Inspect the options that are set in the “Debug All” rule. No changes from the defaults are needed, so ensure that the rule matches the screenshot below, and hit Save Rule.

Figure 15: Starting the "Debug All" rule.

Switch over to the Streams tab and, to start intercepting traffic, click the ‘Intercept’ and ‘Auto Send’ button. Later on, if we need to do interactive manipulation, we’ll turn Auto Send off; but keep it on right now for testing purposes.

Once everything is configured, switch back to the testing VM and browse to an SSL site (such as https://www.google.com). The browser will report an SSL certificate error-Mallory is generating a fake SSL certificate and then re-encrypting the communications to the target server. Confirm the security exception, and the target page should load. Switch back to the Mallory VM, and we can see the request in the intercepting tab.

Figure 16: Mallory has captured an HTTP request sent via SSL to – google.com – on port 443.

FIX over SSL

So Mallory can successfully intercept SSL traffic (albeit with some more or less unavoidable certificate errors), but our thick client is sending SSL-encrypted-FIX, not HTTP. First, we need to identify which port (or ports) the thick client is using to send data. I was given this information (port 32001, in my case), but if you don’t know which port you need to intercept, use Wireshark to monitor outgoing traffic and isolate your target traffic. Add a line to the Protocols tab for the identified port:


Click Apply to save changes. For testing purposes, keep the “DebugAll” rule enabled, and make sure Intercept and Auto Send are both enabled.

We’re not quite done yet. If you fire up your client immediately, we’ll end up with errors like this one:

Figure 17: Client refusing the SSL handshake.

The client refused to handshake to Mallory, since Java was (correctly!) flagging Mallory’s generated SSL certificate as unknown. In a nutshell, we need to import Mallory’s CA certificate into the Java trust store for our application. In this case, there are two options:

  • The thick client had a configuration file with an application-specific trust store called “client_truststore”:
    <ssl dir="config"
    However, this trust store is password-protected, so adding a certificate is non-trivial.
  • The Java Runtime Engine installed on most systems has a system-wide trust store file. On my system, this file lived in:
    C:\Program Files\Java\jre6\lib\security\cacerts
    This trust store is also password protected, but the password is ‘changeit’. Obviously, nobody changed it.

Once we know where our trust store is, adding a certificate is pretty straightforward. We need three things:
  1. Mallory’s CA certificate, named “ca.cer”(from /home/mallory/mallory/current/src/ca/ca.cer)
  2. The system trust store file, named “cacerts” (from C:\Program Files\Java\jre6\lib\security\cacerts)
  3. The Java ‘Keytool’ application (from C:\Program Files\Java\jre6\bin)

Copy ca.cer and cacerts to the thick client’s working directory. We don’t want to import this certificate into our system-wide trust store, because that could put traffic other than our thick client traffic at risk. Putting these together is a snap. Just run the following command, which will import the Mallory CA certificate into the cacerts trust store:

“C:\Program Files\Java\jre6\bin\keytool.exe” –import –alias malloryca –file ca.cer –keystore cacerts –storepass changeit

Keytool will prompt you to trust the certificate; tell it “yes:”
Trust this certificate? [no]: yes

Figure 18: Adding certificate to keystore

Finally, we need to reconfigure the thick client to use our new vulnerable cacerts trust store instead of the old, secure, vendor-provided trust store. Going back to the application configuration where we originally saw that “client_truststore” change the “<ssl” line to read as follows:

<ssl dir=”config” trustStoreFile=”cacerts”>

Now that the Java thick client is using the trust store file containing the Mallory certificate, let’s see if Mallory can intercept and decrypt the FIX protocol messages:

Figure 19: Mallory performing a MiTM on SSL encrypted FIX traffic.



What we’ve done:

  • Setup and configured Mallory;
  • Routed traffic through Mallory, both HTTP and HTTPS;
  • Added a custom certificate to a keystore and successfully MiTM’ed a java thick client; and
  • Successfully decoded and intercepted the FIX protocol.

Tuesday, May 8, 2012

A Quick Overview of Google Web Toolkit Application Security

By Vijay Agarwal.

One of my recent engagements I had got an opportunity to work on a application which uses Google’s Web Toolkit (GWT). GWT is open source java framework used to create rich internet applications. Both the server and the front end are written in java and all the front end logic is compiled client side into obfuscated JavaScript equivalents and loaded into the browser.

Boot Strap Loading and cache/no cache Files

GWT requires no special browser plug-ins and has minimal cross browser headaches. Typically whenever an application loads, its bootstrap process is kicked off and starts the application initiation process. On the server side, the gwt.js and .nocache.js files handle the bootstrap process and are responsible for performing the deferred binding which loads the configuration, modules, and browser specific classes. During this time, initial configuration steps like browser detection takes place and compatible java scripts files are created which are supported by the browser.

The above processes results in multiple "[MD5 Sum].cache.html" files. These are browser specific files that contain application logic, and are generated post authentication. They are named according to the MD5 sum of their contents and consist of RPC methods, other restricted methods, and sensitive information.

Example cache file names:
  • https://www.xyz.com/testapp/9E871855826913D91F95F8F65F4ED9E3.cache.html
  • https://www.xyz.com/testapp/C2C2D9E9AB0BBFD8B66FD43702FAF3B5.cache.html

Example file content:
 !!$stats&&$stats({moduleName:$moduleName,sessionId:$sessionId,subSystem:TG,evtGroup:j,method:oI,millis:(new Date).getTime(),type:WH});  
 k=vr(b);try{lr(k.b,oF+Oq(k,pI)); lr(k.b,oF+Oq(k,qI)); lr(k.b,ZH);lr(k.b,oF+Oq(k,$H));lr(k.b,oF+Oq(k,$H));  

Since these cache files are generated once the user logs out of the application, these files should be restricted and should not be accessible without authentication on the server side. If accessible, these files may disclose sensitive information.

Client Side Code

Google obfuscates it's code once it reaches the client's browser as an extra layer of security and, presumably, to save disk space. The client side code can potentially contain application data and all of the of components associated with it's inner workings, things like its RPC framework - which can greatly aid an attacker. Google uses all of the common obfuscation methods such as function, variable renaming, reordering and respacing

Authorization and other Issues

Authorization issues seem to come up quiet a bit with GWT based applications since its often adopted by developers who focus more on interface design, rather then security. Because of this all of the major web application vulnerabilities should not be forgotten, particularly those associated with authorization vulnerabilities such as forced browsing, session replay, and parameter manipulation.


Tuesday, May 1, 2012

Installing Lorcon2 on Backtrack 5 R2

Robert Portvliet

Recently I wanted to play around with some of the wireless dos and fuzzing tools in Metasploit, which requires the installation of Lorcon2. I found this to be a bit of an adventure so I figured I would write up a quick blog post for those who may encounter the same issues in the future.

So, the Metasploit documentation states to install Lorcon2 as follows:
 $ sudo bash  
 # cd /opt/metasploit3/msf3/external/ruby-lorcon2/  
 # svn co http://802.11ninja.net/svn/lorcon/trunk lorcon2  
 # cd lorcon2  
 # ./configure --prefix=/usr && make && make install  
 # cd ..  
 # ruby extconf.rb  
 # make && make install  

This sort of worked - when I ran the ./configure, I noticed a bunch of strange warnings about if_arp.h, and wireless.h:

A quick dive into the autoconf documentation (http://www.gnu.org/software/autoconf/manual/autoconf.html#Present-But-Cannot-Be-Compiled) yields:

20.7 Header Present But Cannot Be Compiled

The most important guideline to bear in mind when checking for features is to mimic as much as possible the intended use. Unfortunately, old versions of AC_CHECK_HEADER and AC_CHECK_HEADERS failed to follow this idea, and called the preprocessor, instead of the compiler, to check for headers. As a result, incompatibilities between headers went unnoticed during configuration, and maintainers finally had to deal with this issue elsewhere.

The transition began with Autoconf 2.56. As of Autoconf 2.64 both checks are performed, and configure complains loudly if the compiler and the preprocessor do not agree. However, only the compiler result is considered.

Ok, so those warnings weren't really that bad.


There is still the missing libnl library warning. Installing the libnl-dev package fixed those:

 apt-get install libnl-dev 

Troubleshooting test.rb

With the ruby all set up and installed, its time to run the test.rb script provided in the /opt/metasploit3/msf3/external/ruby-lorcon2/. You'll notice if you try to run it, you're going to get this error:

To make a long story short, after a fair bit of searching I found a very helpful post at http://www.secgeeks.com/fix_for_lorcon2_ruby_1_9_2.html which stated the following:
Faced a minor problem with Lorcon2 wrapper module, in compiling with ruby 1.9.2. Following will fix the issues for those who are facing it:
Change STRCCSTR function in file ruby-lorcon-1.0.0/Lorcon.c at line 443,441:

 driver = STR2CSTR(rbdriver);

intf = STR2CSTR(rbintf);


 driver = StringValuePtr(rbdriver);

intf = StringValuePtr(rbintf);

Hope it helps.
Yes it did Secgeek, thanks very much! However, in the case of Lorcon2, you have to edit three lines instead of two:

Change all three “STR2CTR” on these three lines to “StringValuePtr”. When you are done it should look like this:

After that, running ‘ruby test.rb’ gives us the desired output.

Couple More Ruby Issues

Ok, so let’s test one of the Metasploit modules that use Lorcon2 to see if it works.

No dice…
A bit more searching led me to a closed bug report at http://redmine.backtrack-linux.org:8080/issues/153 which stated the following:

Solution: they should be compiled with ruby 1.9.1 and placed in /opt/framework3/ruby/lib/ruby/site_ruby/1.9.1/i686-linux
  1. install ruby1.9.1
  2. cd to /opt/framework3/msf/external/ruby-lorcon2
  3. ruby1.9.1 extconf.rb
  4. make
  5. copy Lorcon2.so to the directory specified above.
  6. do the same for /opt/framework3/msf/external/pcaprub
  7. copy liborcon* files from /usr/local/lib to /opt/framework3/lib replacing existing files

Following these instructions, I copied the liborcon* files , which were in /usr/lib in my case, to /opt/metasploit/msf3/lib/, and copied Lorcon2.so from /opt/metasploit/msf3/external/ruby-lorcon2 to /opt/metasploit/ruby/lib/ruby/site_ruby/1.9.1/i686-linux/.

Its working! (not completely)

Fired up Metasploit again….. Nice!

Kismet confirms its working.

Then I tried ssidlist_beacon.rb:

Not so nice…. WTF?
When I cracked it open I saw that while all the other wireless modules use Lorcon2, it references Lorcon in the ‘includes’ section. So, I tried changing it to Lorcon2. I fired up Metasploit again:

Better… different error, now it complains about an undefined method ‘channel’. After taking a look at the other wireless modules, I found two others, netgear_ma521_rates.rb , and netgear_wg311pci.rb that did not work either, and gave the same error. They all also used the same syntax to determine the channel

 "\x03" + "\x01" +

While the FakeAP.rb module, which works, uses the following:

 "\x03" + "\x01" +

Using that to replace the previous line fixed the problem.

It works! (for real now)

All kinds of SSID’s in the air now :)

The channel issue seemed to affect the following modules, I received the same error from all of them and when I replaced that line as described above, they all appeared to work properly.

auxiliary/dos/wifi/netgear_ma521_rates         NetGear MA521 Wireless Driver
Long Rates Overflow

auxiliary/dos/wifi/netgear_wg311pci           NetGear WG311v1 Wireless
Driver Long SSID Overflow 

auxiliary/dos/wifi/ssidlist_beacon             Wireless
Beacon SSID Emulator

auxiliary/fuzzers/wifi/fuzz_beacon Wireless Beacon Frame
Fuzzer auxiliary/fuzzers/wifi/fuzz_proberesp  Wireless Probe Response Frame Fuzzer

When running the auxiliary/fuzzers/wifi/fuzz_beacon module, beacons appear to be fuzzing properly :)

As does auxiliary/fuzzers/wifi/fuzz_proberesp:

I wrote a quick bash script to correct these issues and install Lorcon2. I ran it through a few times and all seemed well, but let me know if you expererience any issues.


# Script to install Lorcon2 on Backtrack 5 R2
# By Robert Portvliet
# Foundstone

# Set up variables

echo "[*] This script will install Lorcon2 on Backtrack 5 R2"

echo "[*] Install libnl netlink library"
apt-get install libnl-dev

echo "[*] Downloading Lorcon2 from SVN"
svn co http://802.11ninja.net/svn/lorcon/trunk lorcon2

echo "[*] Copying Lorcon2 to MSF"
cp -r ./lorcon2 $rubylorcon_dir

echo "[*] Fixing MSF wireless modules"
sed -i 's/+ channel.chr/+ datastore['\''CHANNEL'\''].to_i.chr/g' $msfwifi_dir/ssidlist_beacon.rb
sed -i 's/+ channel.chr/+ datastore['\''CHANNEL'\''].to_i.chr/g' $msfwifi_dir/netgear_*
sed -i 's/+ channel.chr/+ datastore['\''CHANNEL'\''].to_i.chr/g' $msfuzz_dir/*.rb 
sed -i 's/Lorcon/Lorcon2/g' $msfwifi_dir/ssidlist_beacon.rb

echo "[*] Fixing Ruby-Lorcon2 before building"
sed -i 's/STR2CSTR/StringValuePtr/g' $rubylorcon_dir/Lorcon2.c

echo "[*] Building Lorcon2"
cd $rubylorcon_dir/lorcon2
./configure --prefix=/usr && make && make install

cd ..

echo "[*] Building Ruby-Lorcon2"
ruby ./extconf.rb && make && make install

echo "[*] Copying Lorcon2 libraries into Metasploit"
cp $rubylorcon_dir/Lorcon2.so /opt/metasploit/ruby/lib/ruby/site_ruby/1.9.1/i686-linux/
cp /usr/lib/liborcon2* /opt/metasploit/msf3/lib/

echo "[*] Finished, fire up a wireless module and see if it works"