Sunday, October 27, 2013

Reverse Engineering Automation using Pydbg - I

Pydbg is an open source Python debugger. I've been using Pydbg for many days to automate many boring parts of reverse engineering. In this post I will share one technique sometimes I use for crash debugging.

So, suppose after fuzzing an application we found an interesting crash. And we want to get into the root cause of this crash. It can be sometime very difficult to find root cause of any crash because may be corruption happened inside one function but you are getting access violation inside a different function.

I'm not saying its the most efficient way to trace application flow but sometimes I find it very helpful.

Here I will use one sample crash of "SampleParser.exe". We have two files. One is the file which is crashing the SampleParser.exe and another is the base file on which our Fuzzer did modification. So we have a reproducible crash and we want to reach to the vulnerable function causing the crash. So before we start reverse engineering, we must a clear view of call graph of the application. Obviously it has many functions. Not all of them are involved into parsing input files. First we will narrow down our RE scope to the functions which are taking part into parsing the input file.

Finding out Subroutines taking part in File parsing:

To find out which functions are taking part in parsing the input file, we must have all functions belongs to SampleParser.exe. How how to get that list. Here IDA pro can help us getting the list of all functions. Open up the executable using IDA Pro when its completely loaded, From function window just you can get all function list. (If the application loads arbitrary DLL at run time for parsing input file you need to open the dll file with IDA Pro. )


Now just copy all functions from there and put it in a text file and save it as ida-export.txt. Now we will run the application inside the pydbg and do following things.
  1. From the text file ida-export.txt, we will only take those function addresses which contains the word "sub_" and set a break point on all of them.
  2. Next we will run the program with pydbg.
  3. If there is any break point hit, we will print the value of EIP in command prompt. 
Here is the python script to do the above steps. (Make sure you named the function list ida-export.txt )


Time for The First Run:

So when we start the application, we will get few function addresses in command prompt. So these are the function, responsible for starting up the application. For obvious reason we are not interested in these function.

But we will simply copy the list from command window and paste it in an excel sheet for later analysis.


Now the application is running and our debugger is watching it. So we will open the base file using the SampleParser.exe (The base file is the file, on which our Fuzzer did modification, and this file should not crash the application).

Now in our command window we will see some new functions are getting called and after few seconds when the file is completely loaded inside SampleParser.exe , it will be idle and you will not see any new call in command window. Here roughly we can say these are the functions, responsible for parsing the input file. Again we will copy the list from command prompt and paste it in the next column of excel sheet.

So now we have an excel like this.


And we have a rough list of functions responsible for parsing/loading the input file.

Now we rerun the target application using the above script, and this time we will open the input file which was causing the crash. This time we will get a list of functions but after few seconds the target application will crash. Now again we will copy the new list of function from command prompt and paste it in the next column of excel sheet. So the final excel look like this,


In above excel we can see, we ran the application thrice and function calls upto the blue line are common. At this level application is started and its running.

Below the blue line, few functions are marked in Green ,We see this calls when we feed a normal file to that application and the application starts parsing the file. So these are are the function responsible for parsing we can roughly say.

In the next column the red marked function is where our SampleParser.exe program crashed with an access violation. We can see in the 3rd attempt there are few common function which tell us that it started parsing the file but it crashed suddenly due to some error.

From this analysis now we have 5 function involved into parsing the input file and we are pretty sure any of these did something wrong for which we got the access violation.

0x004057d0
0x004057c0
0x004014a0
0x00402470
0x00404210

So now we have narrowed down our analysis scope to only 5 functions.

Fuzzing Facebook for $$$ using Burpy

Fuzzing is an automated / sometime semi automated software security/bug testing technique which allows us to find different types of bugs with very less efforts. It actually involves providing invalid, unexpected, or random data to the inputs of a computer program. The best thing about fuzzing is, you spend few sleepless nights to write your Fuzzer, and after that you just sleep, and your Fuzzer brings you bugs (or money some time ;)) without any positive effort .


Months back I have blogged about two (this & this)XSRF vulnerabilities, I've found in Twitter application. Both XSRF bugs were found using a web application Fuzzer I've developed,I named it Bupry. I've already shared that tool. You can download the tool from my GitHub page.

The tool is pretty simple, straight forward and flexible. You can easily write your own application specific modules to perform various test cases. Burpy actually takes Burp suite log as input and after that it parses all request response from the Burp log xml file. After parsing that log it performs various tests depending on the module you've provided. In this tool I've also included on raw http request manipulation library which is rawweb.py. You can easily manipulate or modify raw http requests using this library and its very simple. In this post, I am going show how I wrote a Facebook application specific plugin for Burpy to fuzz Facebook application.

So, like Twitter , here also in Facebook, my target was to find broken XSRF protection, in an automated manner using Burpy.


As I've already said, Burpy takes Burp suite log as input. So to do that,I've opened up Burp proxy and started surfing Facebook application randomly with a test account. At the same time Burp suite was capturing all the request responses in background.

So after that, I exported the captured log from Burp. Now here, Burpy's job would be to parse burp log and get a list of all http request (normal client's requests without any modification)present in the Burp suite log and depending on the modules provided, it will modify/manipulate those raw http request (using rawweb.py)and re-send them to web server. And depending on the response, Burpy will generate an HTML report powered by Twitter Bootstrap. A Sample report with single issue is here.

So I wrote a Burpy plugin which removes the xsrf token parameter from all raw http request found in burp log, and re-fire them to server one by one. Now like twitter Facebook also behaves in same manner every time, when you send any request to server using without XSRF token ( XSRF token name is constant for main facebook application which is fb_dtsg). So if you send any request without this XSRF token, maximum time Facebook will give you back an error saying, Sorry, something went wrong - Please try closing and re-opening your browser window or it will throw 500 Server Error response code.

Now if we remove the XSRF token from each and every request that client side code sends to Facebook server, and if we dont find above mentioned error in server response, then we can say that there is a chance that XSRF token validation is not properly implemented. But Facebook application send thousands of GET and POST request. So its almost impossible to do this manually for each and every request that Facebook sends.

So I wrote this tiny Burpy plugin to automate this test case. It simply checks whether XSRF token validation is present in server side or not, by removing XSRF token from request and replaying it. Since Facebook application always throws a generic error message for XSRF error, So if this error is not present in response after removing the token it returns +ve.


So after running this 10-15 times I've gathered few suspicious request response from Burpy report.But  most of them were technically XSRF but not very critical or harmful. But I was able to track down near about 8-10 pretty serious issues.

So from the next day I started reporting them to Facebook Security Team using their online form.

After few weeks I started getting responses back from Facebook security team. Unfortunately few of them did not qualify for Facebook Bug Bounty program because few were previously known to them and few were not very critical.





etc..
etc..
etc..

Bad Luck..huhhh..:(


But 2013 is not so unlucky. Few bugs did qualify for reward.......:) :) :)



So at last I've earned some money out of Facebook and the best thing was Facebook guys mentioned my name on their White Hat Hall of Fame page which is definitely a great CV builder.





Sunday, September 29, 2013

Inline API Hooking using DLL Injection

In this post I'm going to share one simple example of user more inline API hooking technique using DLL injection. This type of API hooking techniques are widely used for many good and evil purposes. Many user mode or Kernel mode malwares use this inline hooking technique to do bad many bad stuffs.

Please remember this information is for Educational Purpose only and should not be used for malicious purpose.I will not assume any liability or responsibility to any person or entity with respect to loss or damages incurred from information contained in this article.

Inline hooking is implemented by overwriting first bytes codes of any API in order to redirect code execution flow. This type of technique can also be implemented in Kernel land.

So when an inline hook is implemented first instruction of target API is overwritten with a JMP instruction. One example is given below where User32!MessageBoxW is hooked.


First I will write a Hooking dll, and when the dll is injected into any remote process it will hook the function MessageBoxW using inline hooking technique. 

int WINAPI MessageBox(
  _In_opt_  HWND hWnd,
  _In_opt_  LPCTSTR lpText,
  _In_opt_  LPCTSTR lpCaption,
  _In_      UINT uType
);

And it will simply modify the 3rd argument (MessageBox Title ) of the MessageBox API with an another text message (MessageBox Owned!). 

The DLL code is given below:


Run time Analysis:

So now lets attach the hooked process with Immunity Debugger and see how this code works. In this case we know that Notepad.exe uses User32!MessageBoxW API to show alert messages when you try to find any word in any text file. So we will inject the compiled DLL into Notepad process.

First we get the PID of Notepad.EXE from Process Hacker Tool.


Then we inject the hooking DLL into Notepad.EXE process. And when we trigger the MessageBoxW call, we can see the Title of the Alert box is overwritten with the text "MessageBox Owned!".


This is the normal stack structure when MessageBoxW is called.


In below screenshot we can see, when the dll is injected, first instruction of MessageBoxW is overwritten with a JMP instruction and the JMP points to somewhere inside the injected dll (inline.dll)


Below screenshot shows the evil code, inside inline.dll file.


And W00t!!


Detection of Inline Hooking:

There are many free rootkit detection available on the internet.Almost all of them can detect this type of inline hooks(Both user mode and Kernel mode).

Reference:

https://www.htbridge.com/publication/inline_hooking_in_windows.pdf

Thursday, September 26, 2013

Hacking Twitter for Fun - XSRF in Account Settings Change

Though for last few months i'm not much into web application security, But still I feel Web App Sec. is fun. For a special requirement I had to develop a web application security assessment tool ( I think it will be better if I call it Fuzzer) and it was time to give it a real life challenge. I named this tool Burpy. because this tool is totally dependent on very famous application security assessment tool Burp.

Using this tool you can easily write your own web application specific plugins to automate various test cases.  You have to feed this tool a Burp suite traffic log (XML dump of http request & response). And depending on the module you write, this tool performs various test cases on the raw http request present in burp suite log.

You can find the details of this tool on my Git Hub Page.

I decided to test it on twitter.com first and unexpectedly I found a very simple yet critical Cross Site request Forgery vulnerability in twitter application.

I started surfing twitter randomly and at the same time burp proxy was enabled and it was logging all request response(twitter traffic). If you've ever played with twitter application before, you may aware of this issue that, if you send any request without CSRF token, twitter application throws a generic error message. And csrf token parameter name is also fixed.

So after that I quickly wrote a tiny Burpy plugin which simply automate below points:


  1. Check if CSRF token present in raw request.
  2. If csrf token present , then it will simply remove the token from request and resend the crafted request.
  3. If the generic error message is present in response body, It means server side check of csrf token is properly implemented hence it will return FALSE else it will return positive response and burpy will write that crafted request and response to final HTML report.


After that I quickly exported the traffic from burp suite (Twitter traffic) and quickly ran the tool on the dump.



It took nearly 5-6 minutes to test all(~~140) request present in the burp log, When its over I opened up the HTML report generated by it and found total 7-8 suspicious/interesting server response. Out of those I found 2 request which was looking interesting. Most critical one is covered in this post .The vulnerability was present in account settings change module. If you've ever played with twitter application you should know that, all profile information changes are handled by this url at server side.

https://twitter.com//settings/accounts/update

Base Request found from Burpy report:


POST /settings/accounts/update HTTP/1.1
Host: twitter.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://twitter.com/settings/account
Cookie: <removed>
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 670

_method=PUT&authenticity_token=88ab8ef7388e544f1c8f22d58xxxxxxxxxxxxxx&user[screen_name]=debasishm89&user[email]=myemail@gmail.com&user[discoverable_by_email]=1&user[discoverable_by_email]=0&user[lang]=en&user[time_zone]=New+Delhi&user[geo_enabled]=1&user[geo_enabled]=0&user[nsfw_view]=1&user[nsfw_view]=0&user[nsfw_user]=0&user[protected]=0&user[use_cookie_personalization]=1&user[use_cookie_personalization]=0&asked_cookie_personalization_setting=1&user[allow_ads_personalization]=1&user[no_username_only_password_reset]=0&user[login_verification_type]=off&user[country]=xx&auth_password=



Crafted Request found from Burpy report:


POST /settings/accounts/update HTTP/1.1
Host: twitter.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://twitter.com/settings/account
Cookie: <removed>
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 670

_method=PUT&&user[screen_name]=debasishm89&user[email]=myemail@gmail.com&user[discoverable_by_email]=1&user[discoverable_by_email]=0&user[lang]=en&user[time_zone]=New+Delhi&user[geo_enabled]=1&user[geo_enabled]=0&user[nsfw_view]=1&user[nsfw_view]=0&user[nsfw_user]=0&user[protected]=0&user[use_cookie_personalization]=1&user[use_cookie_personalization]=0&asked_cookie_personalization_setting=1&user[allow_ads_personalization]=1&user[no_username_only_password_reset]=0&user[login_verification_type]=off&user[country]=xx&auth_password=


The BUG:

As you can see,an anti CSRF token is present in this base request which is "authenticity_token". At glance which was looking fine and quite secure. But the interesting part was, when Burpy removed the CSRF token from the http request and replayed the request, It did not get the generic error message in response body. After manually repeating the step I found that, the server side logic was actually getting failed to validate the token and it was accepting the request.

Now when I went back to my settings page I found all changes I have made are getting reflected. BINGO!!

Another interesting thing you many notices in twiiter that, to change any profile settings if you go to "https://twitter.com/settings/account" page and make any changes, you will find the twitter application will ask you to re-enter your password. In this case even it was not required.

Its time to reproduce the BUG from Twitter:


So from Burpy report I got the crafted request/response but I had really hard time to reproduce this issue because, it was clear that I had to remove csrf token from the POST request but I was unable to find out above mentioned POST parameter combination in any request that twitter sends. I went to settings page made some chnages and when I was clicking save I found that POST parameter combination was not same which were reported by burpy. Spend a whole day to solve that mystery. But finally I found that it was actually one regular expression bug in Burpy which was polluting few POST parameters. And the best part was without that this bad things wont workout.






I hope I don't have to explain much about the criticality of this bug.

Another similar issue I've found on twitter : Here

On 31st August I reported this & this issue to twitter security team using their online form.
Received response from one engineer at Twitter Security Team on 3rd September'2013 saying they have received the report and not to twit or blog about this issue as they are working on a fix.



Twitter fixed this issue pretty fast. On 4th of September I've received one email from Twitter Security Team saying, that the issue is fixed and they need confirmation from my side.



And the last but not the least - The Ultimate CV Builder :D

Twitter doesn't pay security researchers for bugs but they do have a Hall of Fame Page for White Hat Security Researches. So they have added me in that White Hat page. :)





Twitter XSRF Vulnerability - Thanks to Miley Cyrus.. ;)

If you are following Miley Cyrus on Twitter, you may notice that for last few months her maximum twits are getting censored by twitter's automatic explicit/18+ content filter.


When twitter automatically hides any explicit or 18+ content , it also shows a notification like below by which you can permanently disable that filter for your twitter account.


So when you click on that Always Display media like this hyper link, client side code sends below raw request to server.


POST /i/expanded/update_view_possibly_sensitive HTTP/1.1
Host: twitter.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://twitter.com/MileyCyrus
Content-Length: 107
Cookie: <removed>
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

authenticity_token=88ab8ef7388e544f1c8f22d58bd0d6XXXXXXXXXX&do_show=true&scribeContext[component]=tweet


Where the CSRF token parameter name is "authenticity_token".At glance which was looking fine and quite secure. Now the interesting part was, when I removed the CSRF token from the POST request and replayed the above request, I noticed that server was accepting the request and saving changes.

BINGO!!!

This issue is fixed on 4th of September after I reported this issue to Twitter Security Team. 

Also they have added me in Twitter Security Hall of Fame : https://twitter.com/about/security

This issue was also identified when I was testing Burpy. And the module I wrote for twitter application is available here.


Monday, June 24, 2013

PEiD Memory Corruption Vulnerability

PEiD is an intuitive application that relies on its user-friendly interface to detect packers, cryptors and compilers found in PE executable files. This portable tool is very popular among malware researchers for detection of packers / cryptors.



A memory corruption issue can be triggered by feeding a specially crafted Windows Portable Executable file into PEiD v 0.95.Exploitation of this issue requires the user to explicitly open a specially crafted EXE file. So the PEiD user should refrain from opening files from un-trusted third parties or accessing un-trusted remote sites.

Affected Version of PEiD is 0.95. This software is not under active development. Last stable version released on November 6th, 2008. So its still Unpatched.

Advisory:

http://www.securityfocus.com/bid/60730/info

Analysis of this Vulnerability:

Monday, June 10, 2013

Injecting Shellcode into a Portable Executable(PE) using Python


Many years back, there's clear difference between different families of malwares .They used to have their own features specific to one family. But now a days we can see Trojans with worm capabilities or viruses with Trojan capabilities, and so on.


One feature which is very common among malwares that is infecting other legitimate executable files and inject malicious code into them. These are known as File Viruses. File viruses can attach themselves to various locations of the original executable file, replace code, fill in open spaces in the code etc etc. And when the infected file executes, it will first execute the malicious code embedded inside it and then transfer the program control to main executable code. 


A virus infects executable and injects its procedure in to the interior of a portable executable files in many ways. 
  • It can create a new executable section for the code in the target executable for our code to be injected. This technique is described here : 
http://www.codeproject.com/Articles/12532/Inject-your-code-to-a-Portable-Executable-file

  • Inject code between unused space between two PE section. In this article we will use the second technique to inject some code into our target executable.
Please remember this information is for Educational Purpose only and should not be used for malicious purpose. I will not assume any liability or responsibility to any person or entity with respect to loss or damages incurred from information contained in this article.

In this post we will have a look at how can we inject our code (Shell Code) into a legitimate windows executable file.Here I will inject code into Calculator.exe. Here I will use harmless MessageBox shell code generated from Metasploit.

Steps to Achieve This:

1. Generate MessageBox Shellcode from Metsaploit.
2. Fixing the shellcode: Actually we need to modify the generated shellcode little bit to get things work smoothly. We will Add a pusha and popa instruction to the start and end of the shellcode, respectively.This will actually save all register contents and jmp to original entry after completion. So that it will not have any effect of the actual program execution.
3. Next step is to calculate the space left available for our shellcode inside the PE.
4. After that we need to check whether we have enough space for the shellcode in the executable file or not.
5. Now if enough space is available,the most important part is Changing the Original Entry Point of the executable. So that our injected code gets executed first. When our Shellcode execution will be finished the shellcode will transfer the program Control to the actual entry point of the executable.

As usual I used Python's pefile library to manipulate the target windows executable. You can find the code below.









Saturday, April 20, 2013

Fuzzing Monitoring with WinDBG Console Debugger(cdb.exe)

Hi readers, It's been more than three months I haven't written any blog post, Hope you guys are doing well. In this post I will share one of my fuzzing helper script. During Fuzz testing of any application in automated manner, we provide invalid, unexpected, or random data to the inputs of a the target program. The target program is then monitored for unusual behavior.

Generating test case is entirely depending on you, and this is the key of finding good number of quality bugs. But monitoring the target application during fuzz testing is also very important. One can monitor the target application in many ways.


  1. Monitor for Process Termination
  2. Monitor the Event Log
  3. Monitor Application Crashes using debugger

In general I use Python's debugger module known as "pydbg" to monitor behavior/crash of the application I am fuzzing, but I was looking for something better and faster. So I posted a question on NullCon Google group Increasing Fuzzing Speed.

Many great ideas and suggestions came out of the discussion. So from that I finally I decided to try WinDBG Console debugger ( cdb.exe ) as fuzzing monitoring tool. So using this console debugger I wrote on very simple and small python class which can be used to monitor any windows application while fuzzing.
This script doesn't have any test case generator, As I have already told you generating test cases is the key of getting good quality bugs in any application and its entirely depend on you how you generate test cases.
So here is the python class : This script uses "cdb.exe" so make sure you have that installed.
And You can use this class in this way to monitor and track crashes:


Final Thought: I was not very happy with the performance of this fuzzing monitoring script. I consider pydbg is a better options than WinDBG ( cdb.exe )for fuzzing monitoring. If I compare the speed between the fuzzer which I've written using pydbg and this one(using cdb.exe), then I realized that fuzzing speed was much slower when "cdb.exe" was used for monitoring.

Thursday, April 11, 2013

Buffer Overflow Vulnerabilty in VLC Media Player ASF Demuxer


Affected versions  : VLC media player 2.0.5 and earlier
CVE reference      : CVE-2013-1954
Official Advisory:

http://www.videolan.org/security/sa1302.html

Image Source : http://hackread.com/critical-vulnerability-found-on-vlc-media-player/


Details:
When parsing a specially crafted ASF movie, a buffer overflow might occur.
Impact
If successful, a malicious third party could trigger an invalid memory access, leading to a crash of VLC media player's process. In some cases attackers might exploit this issue to execute arbitrary code within the context of the application.
Threat mitigation
Exploitation of this issue requires the user to explicitly open a specially crafted ASF movie.
Workarounds
The user should refrain from opening files from untrusted third parties or accessing untrusted remote sites (or disable the VLC browser plugins), until the patch is applied.
Alternatively, the ASF demuxer (libasf_plugin.*) can be removed manually from the VLC plugin installation directory. This will prevent ASF movie playback.
Solution
This issue is addressed in VLC media player 2.0.x source code repository by replacing a macro with a static inline and improved bounds checking.
This patch is included in VLC's 2.0.6 release.
Windows and Mac OS X builds can be found on the VideoLAN nightlies website.

Thursday, January 10, 2013

JPEG of Death:Zoom Player JPEG File Memory Corruption/Arbitrary Code Execution Vulnerability[0day]


Zoom Player is a commercial media player developed by Inmatrix.It is a slick player of online multimedia content for Windows PCs.

Zoom player version 8.5 suffers from a buffer-overflow vulnerability.This bug can be triggered by feeding a specially crafted JPEG file to vulnerable version of Zoom player(v8.5).Successful exploits may allow an attacker to execute arbitrary code within the context of the user running the affected application.

Vendor Patch:
Vendor Inmatrix. Ltd. has already patched the issue and the affected version is also removed from their site,after I reported it to them.




Time Line:

[*] 16th Dec,2012: Bug found.(https://twitter.com/debasishm89/status/280334928489635840)
[*] 16th Dec,2012: Informed Vendor.
[*] 17th Dec,2012: Asked for PGP Key.
[*] 17th Dec,2012: Shared Technical details.
[*] 31st Dec,2012: Vendor Patched the Issue in version 8.5.1. http://forum.inmatrix.com/index.php?showtopic=13904
[*] 9th Jan,2013: Public release of advisory. http://www.exploit-db.com/exploits/23996/


Exploit Code:


Proof of Concept: