Tuesday, November 26, 2013

EMC Defenders CTF - Week 3 - Contest 14 - Reversing

I played the EMC defenders CTF with a few of my friends a while back. We sadly couldn't complete all the challenges. All the same it was quite a lot of fun. One of the challenges in Week 3 was reverse engineering a 32 bit Windows executable.
While the challenge finished a while ago, I was poking at it a bit even after the challenge finished and finally managed to get a flag. In this post, I wanted to talk a little bit about the various obstacles that were in the way and how I circumvented them.

The first thing that I noticed was that directly running the executable caused it to terminate. So I started digging into it a bit more and found that there were a couple of checks that the exe performed.

- Check if it was being executed in a 64 bit environment
- Check if it was being run inside a debugger







A quick patch of the JZ to a JNZ bypassed both these protections and we were able to proceed without a problem.

After a while at 4010CF VirtualAlloc was called and a section of memory allocated to write "something into" - we don't know what at this time. The next problem was when a CALL was made at 40110B - which called into this section.





Going to that place in memory showed a lot of weird weird code which did not look right at all. Have a look at the screenshot.








Trying to run this code at this point caused an Access Violation straightaway. So I started single stepping the code, and immediately found that code a little lower down started changing. This meant that this was some kind of self modifying executable - a lot of packers use this trick.

I single stepped up to a point and ran again but it crashed again. Single step again - the next section made sense now. I repeated this for quite a while until the entire section started to make sense. What was happening, was that a small section of code would decrypt the next section. The next section would then run and decrypt the next bit. And so on ... until the entire bit unpacked itself.

Here is a screenshot of a packed section.






..And the same section after it's unpacked.







Single stepping the code until 3D0194 eventually decrypted every single bit of the code.












The unpacked code is at 3D0791 (red highlight in screen-shot above). This is how most packers behave - unpack the code to a different location and run it from there. Notice also all those junk ADD instructions after the CALL - more signs that the unpacking ends here. Lets hop over to 3D0791 now and see what's there.









Look at the last instruction and the red highlighted bit below. There is a CMP with 5A4D there and something happening after that. Hmm. 5A4D = MZ in Ascii. And MZ is the start of an EXE file. So it looks like it's searching for the start of an EXE file in memory. That too probably is what the unpacker has done - unpacked the real EXE file somewhere into memory. Where? We don't know as of now.

The red highlighted bits do have MZ and PE - things which lead us to think that the file's somewhere near.. but the other bits like "This program cannot be run in DOS mode.." .. are nowhere near. So maybe... it's not this bit which is the EXE but somewhere else. Where though?

Lets run the code after this and see what happens. We hit F9 and the code starts looping backward .. each time decrementing the place it searches by 1 (ECX register). Hmm. Meaning.. it's searching for the PE header backward. At some point it is going to find this header. Maybe :)

So I started searching for all occurrences of 4D 5A in memory. We got a hit at 3D0181 and with more text which looks like an EXE.







So I set a conditional break-point just after the CMP to break when ECX = 3D0181.








As expected it breaks. Now EDX is compared to 5A 4D. I'd expected that it would find a match and move on. Strangely the program never found a match and kept crashing. So I looked at what EDX was getting set to when the program broke.

Interestingly it got set to 5A CC and not 5A 4D. In other words the instruction CMP EDX,5A4D was failing.. coz EDX was getting set to 5A CC instead and hence never finding a match. Why?

Well CC in assembly is a software breakpoint .. or INT 3 as is often known. I'd set a conditional breakpoint..right? So the 4D at that point was temporarily overwritten by CC and thus the match failed and the app felt that there was no PE file there at all... when in reality there was. Here's a screenshot of what EDX actually contained.












But we know for sure... that there IS a PE file here. Right? So I edited EDX at run-time (and cheated a bit :)) and made it 5A 4D so that the match would succeed.














Suddenly all the code after all started to make sense...and all the right branches started getting selected, which meant I was on the right track. The biggest hint was that the next CMP which compared against 45 50 (start of PE header) succeeded and I exited the "search for PE header" loop. Which means that the header was found. Nice.

There was more memory allocated at 3D09E4 where the entire EXE was copied into 3D0000. Load Library was then called a couple of times at 3D0A9A and the addresses for a ton of functions in kernel32.dll and user32.dll were obtained.

Then I got bored and tried running it after this point to see if it'd give me a flag.. but nope.. program exited again. Aargh :(. More single stepping. I eventually came up to a call at 3D0D46. This call suddenly called to some code which was quite far from 3D0246... it called to 320A0B. Hmm. Interesting..

Eventually I managed to isolate which function was causing the code to exit. I followed the path 3D0915 - 3D097C - 3D0180 - 3D01130. And then I saw this...









So there's 3 CMP instructions ..comparing 3 different locations on the stack to 16,2 and 7E6 in hex and if they "fail" jumping to the end of the code which is 3D0171 (Screenshot shows 261171 because I wrote this blog over a couple of days and the addresses changed :D... just replace 261 with 3D0 and continue reading).

What is it looking at? Lets convert all those 3 to decimal - and it comes out to 22, 2 and 2022. Hmm. 22-2-2022. 22nd February 2022. And look at the call just before that - GetSystemTime. What'll happen if we change our system date to 22nd Feb 2022 and proceed? Let's try.

No.. that didn't work and the program still exited. So there's something else which is calculating those numbers so there is an exact match. We could sit and play around and possibly find the right match..but maybe..we do not need to and can just patch the 3 jumps. I just toggled the ZF thrice... and passed all the conditions so the program exited normally.

No more changes....and I eventually made my way over to 3D009A where there seemed to be some kind of comparison happening with all the sections of the executable..and the right path chosen when one landed on .bss.. one of the sections.






Then there seemed to be a bunch of junk copied over to 18F5CC. But I looked to be coming closer.




And then finally, there seemed to be an XOR with 5E and a MessageBox popping up with..a FLAG?






Maybe..maybe. Yessss.. Finally :)








Unfortunately I couldn't submit the flag since the contest was long long over. But still... it was nice to finish the challenge :)

Thursday, November 21, 2013

Are you sure you're clean?

I do a ton of penetration testing as a tester. I've been doing this for quite a while now - nearly a decade. I advise a ton of peers, juniors, clients, non tech users .. well pretty much anyone about how to stay safe. I know all of this. And yet.. recently I inexcusably slipped up.

One of my Virtual machines which I'd cloned to test a thick client at a client site had a few viruses on it. One of them was C:\Windows\update.exe which did not sound good in the least. Most I found in Temporary Internet Files of the Local service and Network service accounts and there was 1 more EXE file somewhere.

The malware didn't behave like how it was "supposed" to based on the description on the website. So maybe they were all benign...and I was good. But that still doesn't explain how they got on to  my disk in the first place...and what they were doing a VM which also handled customer data. The worst part was that it had probably been lying there for a while without me noticing it. Most probably some remnant of my own research..but I can't be 100% sure. In short.. it was downright dumb on my part. No excuses.

So that made me relook at my setup and I have since gone on a drive to clean it all up. I dumped all my VMs (still in progress) and created everything from scratch from the ISOs, updated them, will harden them a bit and take snapshots of the clean state.

I deleted all my malware analysis images, reversing images and will recreate them from scratch and snapshot those too. So in the end here's a list of the VMs that I will eventually have.

1) WinXP 32 bit
2) Win 7 64 bit
3) Ubuntu 32 bit
4) Ubuntu 64 bit
5) Client WinXP machine + Word + Visio
6) Linux dev environment
7) Windows 64 bit reversing
8) Linux 64 bit reversing

All of them updated, hardened (services turned off) and snapshots taken. Ideally I'd just move everything on to a separate machine..all my malware... but I don't yet have another machine. Once I get that, I'll move all my reversing to a separate machine.

Overall though - you're not immune from doing stupid things. You may know but it doesn't mean you're perfect. Hopefully this post will help all you guys who dabble in multiple technologies all the time - to serve as a reminder of what can and does ..go wrong at times.

Saturday, October 26, 2013

SoapUI - Client side cert - Burp

Many of you who've Googled around for SoapUi - Burp would have seen my earlier post on it, and also a cooler post here.

This time I also had a JKS client certificate that I needed to send to invoke a web-service method. Turns out that while Burp accepts certificates..it doesn't directly accept JKS certs - you need to convert it into PKCS12 instead.

You can easily convert a JKS cert into a PKCS12 cert using the keytool utility that comes along with JDK. Here is the exact command that you need to run to do that.


keytool -importkeystore -srckeystore -srcstorepass -destkeystore -srcstoretype JKS -deststoretype PKCS12 -deststorepass

Make sure that you use this exact command. That's coz there's plenty of other interactive variants to this..but using any of those turn up with a number of weird errors related to incorrect passwords or padding or something else while attempting to import the cert.

Once you have the PKCS12 file, navigate to Options - SSL - Client SSL certificates and add your certificate there.

Configure SoapUI to talk to Burp now as per this or this.. and you should be all set. Have fun :)

Monday, October 7, 2013

Sharif University CTF - 2013

I played the Sharif University CTF 2013 with my CTF team. Wrote up a short summary on the challenges I could complete successfully. I could complete the following:

3 Trivia
Web 100
Rev 100
Forensics 100

Write ups for all of these is available here - https://www.dropbox.com/s/lyzm0rbxn2xa50n/SharifUniv_2013.docx

Wednesday, September 18, 2013

Installing Glassfish on Ubuntu 12.04

This is what I needed to do to get the Glassfish application server running on Ubuntu 12.04.

a) Install JRE for Ubuntu 12.04. Download the version applicable for you from the official website.

b) Configure your system to use the JRE you just downloaded. You can do this as follows:

---- First add the version of JRE you downloaded to the list on your system.

sudo update-alternatives --install /usr/bin/java java /bin/java 0

---- Then ensure that all Java programs will use that version.

sudo update-alternatives --config java

c) Install a JAR archiving program. I used Fastjar from the apt repository.


sudo apt-get install fastjar

d) Download the Java EE SDK with Glassfish and JDK from the official website. Make sure you download the version applicable to you.

e) Once the download is complete ensure that the file can be run. If it doesn't have executable permissions, run chmod 755 to make it executable.

f) Run the installer using ./filename and follow the prompts. If you're lucky everything should go well. If you're not it'll hang at the penultimate step, taking forever to create a new domain.

g) The problem apparently is with Glassfish and some funny bug which needs your real hostname to be in the /etc/hosts file. At least that's what fixed it for me. Here is what my /etc/hosts file looks like.

127.0.0.1    javaee    localhost.localdomain    localhost
10.0.2.15    javaee    localhost

Maybe you don't even need the 2nd line. Maybe I'll confirm that some day. Or someone will :)

h) Reboot once (maybe not needed) and run the installer again. All should be good this time round.

i) You can also Cancel the installer if it hangs while creating a domain and create a domain manually using asadmin as follows.
sudo ./asadmin --user admin
asadmin>create-domain
asadmin>start-domain

... and follow the instructions there. Have fun :)

Monday, September 9, 2013

Truecrypt - Permission and Mount problems

I use Truecrypt files all the time on top of my Full Disk encryption for all my sensitive customer data. I also use sshfs to mount a remote filesystem over SSH and then transfer files from my Truecrypt volume to the server.

What tended to keep happening was that when I copied files onto the server, the files would be editable only by me and not by other members of the group. This was a problem as multiple people work on a single project.

After a bit of research I found out that my local truecrypt volume was being mounted with permissions of rwx --- --- meaning just I, the owner had access. Then, when I copied files from that volume to the server, those permissions were being retained.

The solution to this was to mount my local truecrypt volume with a umask of 017. This would mean that the owner and group would be able to edit the files after I uploaded them. Problem solved.

One day though, I needed something from an older truecrypt volume and found that I couldn't mount it. I kept getting an error which said - mount: wrong fs type, bad option, bad superblock on /dev/mapper/truecrypt1

Huh? Corrupt volume? I restored the truecrypt volume header from the backup it stored internally (look at the Truecrypt docs for how to do this) and tried mounting again. It still failed. After a little Googling to no avail, I started thinking what I'd changed.

Mount options. Umask. Removed the Umask mount option. Tried mounting. Works. Ha. So apparently, since I didn't use the umask option when I created the old volume, it wouldn't let me mount it if I used it. Probably a good reason for it...don't know what :)

So now, I mount Volume 1 without the Umask and Volume 2 with the Umask and both work. You can set and unset the Umask in Settings - Preferences - Mount Options and type umask=017 there.

There's another way to do it. While mounting the volume without the Umask, you can click on Options at the time of entering the password and set/unset the Mount options there. Doing this means the default mount options will be with the Umask.

Thursday, August 15, 2013

Reverse Engineering DLLs

A DLL is usually imported by an EXE. A DLL usually has a number of functions that the EXE can usually directly use. If you want to debug an EXE in OllyDbg, all you need to do is load it in Olly and set a breakpoint on the entry point of the Exe. If you want to debug a specific DLL though, it's not that straightforward.

There's 2 ways of doing this:

a) Open the DLL in Olly. If you also have an EXE called LoadDLL.exe in the Olly directory on your hard disk, LoadDLL.exe will automatically pick up the DLL you want to analyze, load it and stop at the entry point for the DLL. This though seems to work only for Olly 1.10.

b) The other way of doing this is to tell Olly to break each time a new DLL is loaded. You can do this by going to Olly's (2.01) Options - Debugging - Events and tick the box which says 'Pause on New DLL' and OK your way out.

The next time you load an Exe which in turn loads up DLLs at runtime, Olly will break each time a new DLL is loaded. So you can keep hitting F9 (Run program) until you reach the DLL you want to debug.

Now you can debug the DLL as you would debug an EXE :)

Thursday, August 8, 2013

My first ever Defcon

Defcon was something that I'd heard about for a long long time and I was pretty excited to finally be able to attend it. Matthew and me landed in Las Vegas at about midnight on the 31st and took a cab to the Rio.

The first thing that struck me..as I looked through the cab windows was how bright everything was. I'd always read about Vegas and its colourful night life but seeing it firsthand was..something else. If you think Times Square at New York is bright..then you should definitely come to Vegas at least once in your lifetime :)

Rio's very close to the airport and the roads were quite empty at that time, so it wasn't long before we arrived at the hotel. I pinged David who'd kindly stayed awake so I could get in to the room without any trouble. We talked a bit..after which I unpacked and headed off to search for some food at 1:00am. Sadly, there weren't any all veg places inside the Rio; for that matter...there was exactly one hotel open at that hour - The American Grille. The menu on the wall outside the restaurant was NOT promising. The only thing that was vegetarian was rice and fruit. That's IT. All the same I had a short discussion with the bartender which er went somewhat like this..

AD: Hey..do you guys have anything vegetarian on the menu?
Bartender: (Looks me in the eye)... Looks down...starts laughing..shakes his head in slow motion...Laughs more...
AD: (Yeah Yeah very funny). Bah.

... I ended up eating fruit and a smelly (I don't even want to think what it smelt of) plate of rice at 2:00am. Luckily I was extremely tired and dropped off very quickly.

David and me got up at around 6 and went and stood in the gigantic line for Defcon badges. We had the pleasure of speaking with a SysAdmin from France and a dude who worked in the Fraud department of a bank. We had quite a few interesting conversations about the culture in the different countries. I quite like talking about the culture in these different places...where you can just do away with all the usual 'polite social' babble and just talk. If you want to exchange names..go ahead. If not..that's fine too. I never met the guys in the line again..but enjoyed an hour with them..with zero expectations. That's probably how life is best lived...if you expect nothing. Oops..I started again ;)

The guys managing the herculean lines were incredibly efficient and we got our badges in less than half an hour. Anywhere else...that line would have taken at least a couple of hours to clear. It is amazing how every job can be done efficiently... if everyone does what they're supposed to do..the way it's supposed to be done.

I had the remaining fruit for breakfast and then attended Defcon 101..which was interesting for around half an hour. After that, the cussing and ceaseless focus on being drunk all the time started to get boring. Not that the dudes on stage cared though. They even said...' Are we boring you? Fuck off if we are'. Yep. Sounds about right :). I did just that..heh.

I spent a while roaming all around..getting my bearings of what_was_where so I wouldn't lose my way. At around 12:00 I met up with the rest of the team. It was really nice to see all of them after quite a while. That's one drawback of being in Boston...I rarely get to meet any of them. Although..thanks to those weekly calls..I do get to hear most of them at least. So we decided to eat lunch. Guess where they went. Go ahead. Guess. It was that super tasty, mouth watering American Grille. Sheesh. Needless to say..I took a pass :)

I spent the rest of the day attending a few talks..since none of the workshops were open on Thursday. Seriously..it'd be nice if they were. There would be some more stuff to do apart from attend talks which I wasn't interested in anyway. Anyway..the talks weren't too bad...although they were reasonably basic. I quite liked the Pentoo talk...maybe I'll give it a spin sometime. Maybe :)

The rest of the guys from Seattle eventually turned up at around 5:00 in the evening. It was good to meet up with Amar after quite a while...and also a lot of the other guys. Met Nora too..a long time after I first said hello about a year and a half ago..while still on contract. John I, Max C, Eby..good to fix faces to all the guys I talk to online in short.

Ian/Joe/Marcus (Dunno who...coz Ian complained Joe was getting a lot of credit :).. so I'll play safe) booked one gigantic limo/bus into which everyone piled in and roamed all around Vegas. There was one pitstop made..obviously...where a few of the guys went in and bought around 500 litres of booze of all kinds. This resulted in Tom playing a terrible game with everyone. He asked everyone to drink a peg? of whisky and eat a Hershey's kiss (chocolate) at the same time. Obviously..all the experienced dudes had no apparent trouble .. but Eby sadly suffered quite a lot and was high/in some discomfort for a while. Amar only cackled at all of it... he's an old hand at all this ;).

Eventually we reached this place called the SkyMall where there is a dome and the roof is painted to look like the blue sky. Parts of the dome are rigged to turn sprinklers on...and generate flashes of lightning and cause thunder to rumble. For a good 15 minutes .. I had no clue we were inside the mall..that's how well it was designed. This was definitely one of the most unique places I had ever seen.

Hopped in and met up with Max.V (who was my first ever project lead while I was on contract) and Jon Boyd...good to see him too..after working quite a bit with him. Had a few really good discussions with Marcus on reversing...and later Dinis popped in as well...for a while. Morgan very kindly helped me out with my salads for the night...he always looks out for my food when I'm around, which is really nice of him. Talked quite a while with Tyson and Amar too..outside the hotel....good to speak to Tyson too...after the infamous "experience" in Connecticut ;).

During dinner...there were some er disturbing parts for me...maybe this discussion will throw more light on it.

AD: Reversing blah blah
Marcus/Jon.B/Matthew/whoever: yeah yeah
Waiter: White roasted chicken...who wants
All: yeah yeah we want
Waiter: chop chop chop
AD: ugh
AD: so ..blah blah blah
All: blah blah...
Waiter: Red steak
All: yeah yeah
Waiter: chop chop chop
AD: (oh fuck off)

Repeat a million times... :D

Just when it was all finishing..Dinis turned up...and the whole saga repeated itself just as I was finally hoping it'd ended. Thanks Dinis for coming late :D

ah well.. it was a steak house really..so for me to expect Indian vegetarian delicacies was a little er.. unrealistic ;) .. but the meat chopping exhibition was not a lot of fun..frankly. I've got a very thick skin...but this was a bit too much even for me. The rest of the dinner though..thanks to all the guys was a lot of fun and I enjoyed speaking with all of them.

Tyson and me lost our way in the mall and had to run a lot..one way and then the other until we finally found the limo again..and got dropped at the Rio. A lot of the guys went off for booze session 2 at a Microsoft Party. David, Garrett and me went off to the room though and slept off..after discussing some deep stuff for a while. I just can't shut up..you know :). I must add here that Amar's plans for reducing his liver's age by another month were dashed by the security guards at the Microsoft party }:)

Day 2 started with a bunch of us having some breakfast at Starbucks and then splitting up to get to different talks. I attended the quite awesome CDMA interception talk where a bunch of complex demos worked flawlessly. It just proves once more...that if you work hard enough and have a clear thought process... the hardest thing is easily doable. Big props to Tom Ritter and the guys at Isec for pulling that talk off.

Lunch on Day 2 was downright awful as the food in the fridge had frozen up and I didn't have a microwave to defrost it. Somehow though I ate it up :D. I spent quite a while in the Tamper village learning to break seals open. The simplest one was using Acetone to peel labels off carefully without being detected. I tried to break open quite a few other seals using these things called shims (pieces of Coke cans :)) but was a miserable failure at all of it. Oh well. I'll learn.

I spent the latter part of Day 2 in the hardware village and soldered my first ever piece of hardware. That gave me a huge kick and I was very very happy that I did something new. The feeling of achievement is a unique thing...it never gets old. I was too late to join the rest of the guys for dinner. Not that I'd have eaten anything anyway ;). Some more rice and chips for dinner, a little TV, a little Kindle reading..some more discussions with the guys on tons of things that I cannot remember .. I hit the hay. Seriously...I was in Vegas..and instead of ogling at babes in strip clubs...I read the Kindle? Yes Yes.. much better :)

Day 3 on Saturday...David, Garrett and me went off to Palms for breakfast... where they actually let me eat my own food..interestingly. That wouldn't have been allowed in India. Those pancakes looked delicious...but sadly I couldn't eat any of it..coz of my rules. I spent a good 5.5 hours doing a surface mount at the hardware village. The end result was a weakly blinking LED which was utterly useless. All the same..it blinked...and it was the result of a lot of painful work. So Im happy.

The other good thing was that I discussed a ton of things with a ton of people whose names I don't know and I probably will never ever meet..but all of whom helped me a lot. I prefer it this way without all of that artificial societal crap that everyone deludes themselves into thinking is 'necessary'... life long. Also... I managed to skip a meal. Yay. One less meal at some terrible hotel.

I think I saw Amber's talk on suicides where she talked a bit about Aaron Swartz and on how to detect the signs of suicide. I thought it was a really great talk..and I hope to learn a little bit more about it going forward.

Met up with Amar and Nipun and talked a bit. Met people I never thought I'd see again. The world is a super small place. Spent quite some time playing the fool along with Zak. If you're reading this Zak...I hope you realize that you've scarred me mentally lifelong by bullying and harassing me that evening and showing interest in a lot of extremely 'delicate' rest room related issues. I hope you reflect deeply and do some soul-searching. :)

We all walked down to Palms where I found out that I had to spend 25$ and buy the sea-food buffet and then eat just a salad. That made no financial sense whatsoever so I came back and ate more rice and chips. Spent some time watching some people selling houses to people on TV. I quite enjoy that show. David got back at around 10 in the night following which we talked about a lot of things (Ayn Rand included (finally :))) for a couple of hours. Garrett was painting the town red that day and didn't get in till 5:30am  or something. I think this was the night of the famous pool party which I too attended and had a blast. Oh wait ;)

I attended Dinis's highly energetic talk on Sunday morning and met up with him as well. It was cool to see him and talk a bit. Unfortunately, he was surrounded by too many people so I couldn't talk too much with him..maybe some other time. That apart Sunday was pretty uneventful...and I kept hanging around here and there until the Defcon closing conference.

The Defcon closing showed me a side of America that I hadn't seen. There were a lot of guys who were moving on from the Defcon management team..after a ton of years of loyal service. Jeff Moss gave a number of extremely genuine tributes to all the guys moving on. The thing that touched me a lot though..was the obviously genuine affection that the rest of the team had for these people. There wasn't a bit of that ..that was fake or made up by anyone. And these are all big bad hackers...who do not have feelings and supposed to be extreme egotists who give a damn about anyone. For them to come out, express themselves and talk so well... that for me was pretty cool. It also showed me that... people.. deep down... are all the same. You just have to look beneath the surface..and not go with your instincts.

I spent a lazy evening with Amar and Eby on the Vegas strip after which I headed back to the hotel and then flew back to Boston the next morning with Matthew.

Considering the size of the event...and the complexity of it all...and having to manage a group of people who call bullshit out better than most other professions...and doing it so well...Defcon for me was an absolute hit. Sure there's little cribs...but overall...big big respect to all those who made that happen.

Hopefully... I'll be back for Defcon 22.

Friday, March 8, 2013

Restrict signed Java applets


There's a ton of information on the Internet on how to sign Java applets and restrict unsigned Java applets as well. Very strangely there is very little information on doing the same for signed applets.

I did manage to find information which eventually helped me out; just that it took an insane amount of searching. Hence this little blog..which just collects all the information I found and puts it in 1 place.

First of all, the reason (as you already most probably know) to restrict signed applets, is that they're all powerful and can perform dangerous file I/O and network operations. So it's a nice thing to be able to restrict them from doing so, if needed. So here are the steps to do so, in a nutshell:

a) Sign your Java applet using keytool and jarsigner. A self signed applet is sufficient for demo purposes. The same logic can be used in case a trusted CA signs the certificate.

b) Once the applet is signed it's usually packaged into a JAR file prior to deploying it.

c) It's then deployed by embedding it into the HTML of a web page.

d) When the user visits the page, there's a pop-up which will now appear, asking the user to grant the applet additional permissions. Note here that if you click Run, the signed applet has complete control and can make numerous file and network I/O calls. If however, you click Cancel, you're not granting it permissions. The applet still runs (contrary to what one might intuitively think) but behaves like an unsigned applet.

e) What we now want to do though, is to limit what the applet can do, when the user clicks Run. For example: If all the user wants to do, is write to /tmp and nothing else, why should it have a million other privileges?

f) There's 2 ways to do it. One is to call every single relevant method in the applet from JavaScript. The second way is to write a policy in java.policy. Without frustrating you further, I'm going to show you, with a little sample code on how to do both.

g) First of all here is the Java code that I used as a POC. It's grabbed and tweaked from some tutorial online and not my own.


import java.applet.*;
import java.awt.*;
import java.io.* ;
import java.util.*;

public class FirstApplet extends Applet{
  public void init() {
    createFile("/abc/testsignapplet.txt");
  }
 
  public void test_HTMLbutton_method_invoke() {
    createFile("/abc/booboo.txt");
  }

  public void test_js_onload() {
    createFile("/abc/doodoo.txt");
  }

  private void createFile(String filename) {
    FileOutputStream out = null;
    try {
      out = new FileOutputStream(filename);
      out.write(("Testing jar signing process...:" + new Date()).getBytes());
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally  {
      try {
        if(out != null) {
          out.close();
        }
      } catch(IOException e) {}
    }
  }
}

h) Here is how you must call the public methods of the applet from either an HTML element or from JavaScript. The line in the last < script > block which embeds the applet is possibly not the best way to do things; it's just there to show you guys how to call a method via HTML and JS, which is the point of the post.









i) Doing so, will cause the applet to still behave as an unsigned applet. If there's any malicious code in any of those functions, it's not going to be able to break out and cause havoc.

j) The other way of limiting the operations an applet can perform is by editing the file called java.policy. On a Ubuntu system, by default this file is inside your home directory. It is named .java.policy.

k) Back the file up and then delete all the lines in that file. Now add these lines to the file. This limits the applet loaded from http://localhost/applets/ from writing to any other directory except /abc.

grant codeBase "http://localhost/applets/*" {
  permission java.io.FilePermission "/abc/*", "write";
};

l) Note that a cool GUI tool called policytool can also be used for this purpose. If you have JRE or/and JDK on your machine, you should have policytool as well. You can add/edit/remove policies using it as well.

m) Test your applet using appletviewer first. It's a tool which you can use to check if your policies are working properly, before deploying the applets everywhere.

appletviewer -J-Djava.security.policy=/home/arvind/.java.policy sample.html

n) If the results are as expected, launch the applet in the browser. All the HTML and JS calls to methods should be blocked :)

----------
p.s - It's a good idea to have the Java Console launched while you're doing this stuff. It throws exceptions that you can then see and modify your approach accordingly. The Java Console can be launched using javaws -viewer and ticking 'Show Console' in the Advanced Tab.

Other Java related settings can be tweaked too in here. A good guide to follow can be found here - http://seanthegeek.github.com/harden-java/

Thursday, January 31, 2013

Virgin mobile - Customer service

I was having trouble paying my monthly bill so I call up Virgin customer support. Here's what happens. I'll let the conversation speak for itself.

Virgin Customer Support = VCS

Me: Hey..I cannot seem to pay my monthly charge. Can you help out?
VCS: Sure..what's your phone number.
Me: Gives number
VCS: Thank You. (Does address and other verification)
VCS: Can you give me your mobile Pin? (Mobile pin = password)
Me: Huh? Do you mean my login password?
VCS: Yes correct
Me: Why do you need my login password?
VCS: Because I need to see why you can't pay your bill
Me: Why do you need my "password" for this?
VCS: (Repeats)
Me: (Tries to explain) This is like asking me for my Email password. Would you ask that of anyone?
VCS: (Ignores) If you don't remember your password...I can send it to you?
Me: Huhhhhh !!! .. still... lets play along. Okay..I say
VCS: Sends text message. Password happily on my phone in clear text now :-o
Me: Reads out pin...(still in shock)
VCS: Thank You (so they had it...just wanted to verify. Ah that's fine then. Good grief)
VCS: Okay I am going to check what happened to your payment
VCS: Okay it didn't go through. Lets try it again.
VCS: Can you give me your card number? and expiry date?
Me: Gives details
VCS: Can you also give me your CVV?
Me: Huh !!! (Another WTF moment)
Me: Why do you need my CVV? That's sensitive information.
VCS: Oh never mind..you have saved card info here. Click. Click. Done.
Me: Er..thank you.

Now there are multiple problems here which I quickly list.

-- My pin is in clear text there. Anyone who has access to the records can basically screw me if they wanted to. How much ..is debatable but at the least they can login as me.

-- They use a password as a verification tool. And when the customer doesn't know, hey no problem...we'll send it to you. So if there's a targeted attack..and someone's phone is flicked he's screwed.

-- Asking for CVV. I don't think you need this to complete a transaction. And assuming it is in fact needed, isn't it risky to give someone this on a call? They now have all my card related information and can misuse it anywhere.

-- Lastly..I hope all my card info is not stored in plain text in the DB. I really don't know.

So..while I did end up paying my bill, this experience shook me a little. Thoughts?

Friday, January 25, 2013

JavaScript application testing - Firebug - Part 2

I wrote about how one can use Firebug over here. Today I'll extend that a little by introducing a few of the features I didn't touch upon last time. There's not too many left as I did the bulk last time, but hey..let's complete stuff :)

So the last time, we talked about setting breakpoints inside Javascript to look at code. We'll do 2 things now..firstly we'll actually set those breakpoints and take an actual application and see how these breakpoints help and secondly we'll introduce DOM breakpoints and see how those can be helpful at times.

So here's a client side application. On logging in as an Admin user we can see the first image and while logging in as a normal user, we can see the second image.


The goal here is to try and make those extra links appear for a normal user. Since the purpose of this blog is to just show you what breakpoints can accomplish, I won't dive too deep into how I identified the right place to set the breakpoint. Here I know that the critical place is line 4598.



The application is checking if the current user has a role of 'Edit Articles'. Where is it checking? It's looking into the TM.Gui.CurrentUser.userRoles element. Now how do we know what that contains? Well there's 3 ways. The first way is to look directly at the DOM element in question by navigating to the DOM tab and expanding nodes till you reach that element.



The second way is to do this through the console by typing in the whole path. If that path exists, the values will be displayed. Autocomplete by the way is enabled in the Firebug console...use the arrow keys to complete a word (left/right) or view possibilities (up/down) and hit Enter 2 times when done. If you type the whole thing out you need to hit Enter only once.








The final way is by means of something called a Watch expression. This is something completely new. It was to me too a day or so ago :). Navigate to the Scripts Tab and look at the right pane. Now click on watch and then inside the box which says 'New watch expression' and type in the exact same path you typed in the console. Autocomplete is enabled here as well. You can also right click on any property in the DOM and say 'Add to Watch List'.

NOTE though that the Watch is useful only when a breakpoint is enabled. We'll see why very soon.






Coming back to our example, which we've forgotten completely :).. we want to do something so that those 2 extra links appear for a normal user. Now if you've followed through, you'll know that the normal user does not have the 'EditArticles' role at all. And if she does not have the EditArticles role, she cannot get those 2 extra links. This means that we'll have to somehow edit the DOM and add that role in.


If you look at the Watch tab here before editing you can immediately see the value of the specific property without changing tabs to go to the DOM or the Console. You can stay in the Script tab and do it.


If you'd read Part 1 you'll know that this can easily be achieved by using the Console. If you haven't, and are frantically right clicking inside the DOM without success, don't worry. Here's how you do it again.





If you look at the DOM, using any of the 3 above techniques you'll see an additional role (EditArticles) that's added.



Let's now hit Continue (F8) and see if we get an additional link. We sure do :). The exact same exercise can be repeated by setting a breakpoint on the isAdmin line (4597) and adding the "Admin" role to the DOM. If you'd like to try it out,  grab a copy of TeamMentor from Git.

DOM Breakpoints

All this while we've been setting breakpoints in the JavaScript. It's also possible to set these breakpoints in the DOM instead and alert us when that particular property changes. Let's extend this same example now, shall we.

On clicking logout, there's a high chance that the DOM is going to get flushed and we won't have access to any of these menus any more. Let's see when exactly the 'role emptying' of the DOM happens.

Navigate to the DOM and expand the CurrentUser node. Right click on the currentuserName element and click 'Break on Property Change'. You now have a DOM breakpoint set which are also visible in the Breakpoints menu in the right pane of the Script Tab (You may have to scroll down). Let's now logout and see if this gets triggered.




Yes! The DOM breakpoint is triggered and points us to the exact line of JS code that was editing the property. Click F8 and then go back to the DOM to see if there actually was a change and you'll find that the same property is now "undefined". Which means the DOM breakpoint did work :). This is extremely useful when you can see the exact path of an interesting element in the DOM but don't know where its corresponding JS code is.




 Other useful features:

There's the 'Break on Next' feature which will break on the immediate next script. I want to see what happens as soon as I click login? Click the Break on Next button and then click Login.






As mentioned by a person who read the previous article, you can set XHR breakpoints if you want to break on a specific XHR call; that's the easiest approach to do things...many a time. Break on the XHR and then use all these other techniques. Similarly you can also break inside the HTML tab when an attribute is added or removed. Make sure though that you're clicking on a leaf node...the last node...the attribute. You can't break on a non leaf node. The same logic applies to DOM elements as well.

If you want to look at the entire Call tree. For example: If you've broken on isEditor and want to know where it is called from you can look at the Stack (middle menu - right pane - Script menu). The most recent function is at the top and the first caller right at the bottom.
















That apart you can edit HTML, add elements, destroy or modify cookies and possibly many other little things. To know everything this fantastic tool can do go on to its webpage and read the documentation :).

Hope you liked this small series. Again..if you  missed it.. here is Part 1.


Thursday, November 1, 2012

Javascript application testing - Firebug

Recently I was testing a Javascript application. By Javascript application what I mean, is that a lot of the business logic was written on client side. Now it's a reasonably well known fact that client side logic is easily by-passable.

There's plenty of ways to do it ..intercept in Burp, delete the Javascript from the cache folder on your disk, create your own forms or use Firebug. Maybe more. Largely though I find that a combination of manual probing to detect where client side validation is being used, intercepting every single request for every file type and then dropping the Javascript request responsible...works.

There are times though, like in my last application where the entire UI of the app is constructed client side, where dropping Javascript will not load the app at all or mess it up bigtime. So Burp, in such cases, while you can still certainly use it...is not the best tool for the job. The next thing you will hear, if you google about 'Client side testing' is that 4 out of 5 people will say - Use Firebug.

Now once you understand it, it's an absolutely fabulous little tool to use but until then, it can get a little frustrating to use. So what I'm going to do here is to just point out the features I use the most and why I do so.

Inspect Element

The first feature that I use a lot is the 'Inspect Element'. You can open up Firebug and click the button that's highlighted in Red below and then move your mouse over the upper half of the page. As you hover over each part of the page, the corresponding part of the HTML in Firebug will start flashing. It's all in real time.

When you're clear which bit of the page you want to look at in Firebug, click on that element. Firebug too will stop flashing around. I tend to use this a lot when I want to look at the attributes set for a particular form. For example: If I want to check if the autocomplete attribute has been set on the password element, I can focus just on that and click. Then I can read the HTML on that page in the lower pane.

















If you want to change the maximum length of an input field in a form, you can double click on the bit you want to change, and enter a new value. The key here is to ensure that whatever you're typing in is syntactically correct otherwise Firebug won't make the change and will leave you frustrated. For example: If you're entering a string, make sure you put it between double quotes.

Javascript

If you want to change just a part of the Javascript on a page, click on the script tab and then reload the page. All the Javascripts on that page will get loaded. Now you can click on the little drop down there (marked in Red) and see all the Javascript loaded. Click on any one to load it up in Firebug. Don't keep clicking on the dropdown marked in Blue. That's just the main tab that you can use to get there.



If it's a small application you might want to manually review the Javascript on each page. Click menu - Let Javascript load - Review. Repeat the cycle. If it's a huge application like the one I was testing though, there's a high chance you'll go mad very quickly :). Trust me. So you need an upgrade to your testing technique. That's where the DOM tab comes in.

DOM

Anything that's loaded in the browser will read/write something from the DOM. Now lets say you loaded a page up which dealt with logging in to an application and you want to check if the authentication logic is client side. That'd be a rare thing and largely quite a stupid thing to do, but it'll do for now :).

So if it is, there's a chance that some JS functions are being called. But you don't know which one and in which Javascript. So as soon as the login page loads, click on the DOM tab and scroll down a little. In whatever Javascript applications I've seen, there's usually a tree full of elements at the top of the DOM. All the reading and writing from/to the DOM happens here. Just below that though there is a large list of functions (all in green font) as shown in the figure below.



Now read through all of those names and make a little list of which functions 'sound' like performing a login sequence. If you click on each of those functions in the DOM, you'll immediately jump to the Javascript which has the code for that function. NOW you can study just that code and see if its insecure. Yes, you're still studying code..sure..but at least the scope is reduced a little.



Setting Breakpoints

Now we've made progress and come up to a point where you know what bit of code is "possibly" doing what. I say possibly, because you haven't actually run it or in this case, clicked on the login button to actually make it happen and see if THAT function is triggered. Let's now confirm that.

If you look at the screen-shot below it'll show you the exact line number on which those 2 functions are called. You want to make sure that those ARE called. So you set a breakpoint on those lines. A breakpoint, for anyone reading this and not too familiar with the term does what it says. It breaks. Breaks what? Execution. Of what? Code. What code? Javascript. When? When I click login.

So I'm just saying..I'll click Login and if the code here is triggered and my guess was right..don't go on. Stop right there. Set breakpoints as follows..set it on the first line of the function and not the definition itself. I'm not sure the line that has "function" is triggered; it may be..I'm just not sure as I haven't had success. Here's a screen-shot with the breakpoints.


Now try and login..

Yeah..actually put in a user-name and password..and login. If your function guess was right, you should stop right where you put a breakpoint. If it doesn't stop, it's the wrong path flow for THAT function. So maybe there's some other place login is called. Search for all such instances..and whenever you see a function with login in it...set a breakpoint.  Here's a screenshot where I've searched for login, a breakpoint has triggered and the credentials I entered can be seen in the Right side pane.



Now it's like Burp inside a browser window :). Read. Edit. Forward. Only the forward button here is the Continue button .. the right pointing arrow. If you want to go Step By Step and see what happens...and many times you will want to do this, you can use the Step Into or F11 key to now proceed line by line and watch the path the code takes. Again..when you're editing stuff..make sure you are syntactically correct. Otherwise the change will not persist.

Adding to the DOM

So the last cool feature in Firebug that I'll go over today is how you go about adding an element to the DOM. So suppose you want to add a parameter called 'admin' and set its value to 'YES' so you can try logging in as admin, you have to use the Firebug console to do so. So first decide where you want to add the property.

















Once you're clear right click on a different property; in this case any root element like PR_TAB_WIDTH and say "Copy Path". Then click on the leftmost tab called Console and paste the path into the bar at the bottom and change its name and value. Like this..


And hit Enter. Now go to the DOM and you should see a new property called Admin with the value YES. It didn't work here of course..to give me admin privileges, but you get what I am trying to say :)






So that's it...start playing around with Firebug, it's a supremely powerful tool, specially when you're testing JS applications. Until next time..Cya :)

Wednesday, October 31, 2012

Salt your passwords = Existing accounts password reset

This one is just a simple conclusion that I drew when a customer had MD5 hashed passwords in his database and we recommended them to salt them instead and use PBKDF as the algorithm of choice.

Now the customer added code in, but left the old code in as well which did the simple hash comparisons. So I asked them why and they said..for old users. I started thinking about it and it made sense. Here's why:

Think of it. I have a MD5 password in the database. Say I add a new column for 'salt' , generate 1000 random hashes..one for each user..and add a new column. I then change the code to query the DB for the 'salt' as well, when a person logs in and run the user's password through the PBKDF function before comparing it with the hash. Looks good?

Sure. Except that no one will be able to login. Why? It's super secure now :). No one can find any more vulnerabilities inside. Jokes apart, what's happening here? Lets say the user's original password was abc123 and it had a 32 bit MD5 hash XYZ. Now when the user logs in something like MD5(user entered password) runs..hashes what he entered and compares it to the stored hash. Match? Login successful.

Now there's the salt. So when the user logs in, the new 'salt+pbkdf' code is triggered. So PBKDF(userpwd + salt) is calculated and compared to ..what? The stored MD5 hash. Is there ever going to be a match? Largely no. Because..there is no way you can predict the salt for a particular hash..BEFORE you store it in the DB. Remember those 1000 salts you generated? All random? Did you check if they'd give you the user's password after "decryption"? Nope.

So since there's no way to get the "right salt" for each user ID, the easiest solution is to force a password reset across users. The next time they login everything will automatically fall into place.

Thursday, October 25, 2012

Incremental code review - MD5 hashes

This one is a reasonably obvious tip to be frank. I was recently doing a code review retest for a Java app. Now I don't know too much Java so I was finding it hard stepping through code.

One thing I knew though was that if you have the previous code base and the current one and are "re-testing" it's helpful to see which files have changed. Now anyone with a little Linux experience or programming experience will immediately say 'diff'. And yeah..diff is fine..but that will give you a very detailed listing in a slightly cryptic form. Its readable enough if you go slow, but it's not the first step IMO. I'd like a slightly more high level view first. That's how I stumpled upon md5deep.

So I go into the first root directory of the old code and run md5deep -rl > old_list there. Then I change directories to the new code and run md5deep -rl -X old_list > changes over here. Basically all it means is that I compared the new list against the old. Once I have my changes, I know that any fixes they made MUST be in some of those files.

Now I can run diff on each of those file combinations to search a little bit slowly. It's the same really..but it gives me a little more control over the process.

A tip here to further reduce changes is to use md5deep with grep to filter your results out. So I knew I was looking only for java file changes...so I could either do something like:

md5deep -rl -X old_list| egrep -i '.java$'

OR

md5deep -rl * -X ~/list_md5_old |egrep -v ".doc$|.DS_Store|.js|xml|changed_files|hibernate" > changed_files;wc -l changed_files

I used the 2nd one :) coz I knew what all I didn't want. If you don't know that..start with what you know and filter on from there.

There's a million ways of doing this of course; I just dropped in what I did :). Here's the blog post which saved me some time..

http://linhost.info/2010/02/checksum-a-directory-with-md5deep/

Saturday, September 8, 2012

Cross Domain XHR

Recently I was doing a project (REST web services) where there was an interesting implementation of a defense against CSRF attacks. You would login to the application and immediately be assigned a session ID in a cookie; along with this you would also be assigned an AntiCSRF token, in another cookie. Now this immediately means that both cookies are going to be sent across to the server each time and going to be verified each time. Hence, if this had been the only defense it would be pretty useless; as the additional cookie does..nothing.

In the application though, what was happening was..the cookie 'token' was read, its value grabbed and a new custom header called X-Security-token added in the header with its value. So if on login I get a cookie: token=abcd, the next time I say...do an Edit Profile...I have a new HTTP header called X-Security-token: abcd as part of the request header.

Now my first thought was, Ha, spoofable...the attacker just needs to write a little Javascript, read the cookie (document.cookie) and then add a new custom header and send the request off.

The data was all in JSON format and I wanted a POC to show so I thought I'd just have a simple HTML file with some Jquery code which would make an XHR request by doing all the stuff I talked about above. The code seemed all okay when I tested it on localhost. As in..I set a cookie with the domain as localhost and value as 'arvind' and tried writing JQuery to pick it up and create a new header. That worked and the request DID read the cookie, append it to the header..and send a request to localhost.

The moment I changed the URL to the actual site URL, the request never even fired. I could understand it if the cookie didn't get sent but the request never fired either. More reading revealed that this was due to XHR's limitation of sending cross origin requests. It just refused to send anything at all; I couldn't even see anything in Firebug. I change the URL to localhost..immediately an XHR request gets fired. I tried removing the cookie and resending it...no luck..same behavior. Posts to localhost. Okay. Anywhere else. Browser doesn't allow sending an XHR request anywhere else. Not yet totally clear what's happening.

The other strange thing though is that there is this addon called a REST client which is installed in the same browser and seems to be able to make calls happily to multiple domains other than localhost.

So the question is..What is the difference between an HTML file hosted on a local web server..making XHR calls to abcbank.com AND a firefox addon making calls (not sure if its XHR as I did not see an X-Requested-With header) to abcbank.com? Why does the latter work?

So as a CSRF protection...it doesn't seem safe but I'm not able to get it working with XHR at least. There's some suggestions elsewhere that some versions of Flash allow this; but right now I'm not sure. I'll update this later if I stumble upon something.