Friday, August 16, 2013

Obfuscated C map generator program Explained

Hello folks ,

Today ,our journey won't be about any topic related to IT security field ,we are going to analyze a C program that became famous the last couple of days ( at least to me ) ,and it uses code obfuscation techniques to make it hard for a usual coder to understand the code ,we are going to walk through it byte by byte until reaching the overall idea on how it's functioning .

Okay ,so let's start by showing the code ,here are two applications i saw lately :

Egypt Map generator

India Map generator

Note :

-I didn't remove any bit in any of the codes provided above ,so all rights are reserved to their real authors ,the coder of the egyptian map  is Eng. Tocka Ayman ,while the indian one ,i found it on StackOverflow ,so its right is reserved to its real coder .

Explanation :

-Let's start by showing respect to the guys who wrote these codes ,i was really happy to waste time and effort analyzing their code trying to de-obfuscate their techniques to reach something useful ,Hats Off !

-We are going to take the egyptian map generator as our study case today ,also im going to use Python to analyze the code ,you can use your best scripting language .

-So let's start the journey ,the code starts with the very usual inclusion for our lovely header files which contain functions explicit prototypes ,in our case ,we included the standard input and output header to use later on putchar() function .
-After that ,we started the main() function with some declarations and one useless initialization ( the variable count ,which has nothing to do in the program ) ,then from now on comes the pain .

-Our main components are two nested for loops which role are to print the characters of the map figure on screen ,let's take a closer look at the header of the first for loop ,we can see the long string in the condition part of the loop ,it looks like this :

After this string ,we can see the indexing part ,which is little bit obfuscated [b+++21] ,this part can be written in a better way as : [b++ + 21] ,that way ,we can clearly see that it contains a post-increment statement ,an arithmetic operator ,and a constant ,in the initialization part we can see that b and c are assigned the constant 10 ,so the indexed part can be solved to 31 in the first iteration ,that means the string is going to start from the 32'th character in the string ,thus we can conclude that the 'real' string that is responsible to 'draw' the map is :

So far so good ,now let's get deeper and ask about what that string is ,what it can do ?!
This is a kind of compression ( or encoding ,if we can say ) ,named run-length compression ,it's a way to compress a bit-stream buffer into a less-in-size buffer ,which means ,instead of having a buffer of more than hundreds binary digits ,we can compress it into less number of bytes by transforming it into another way of representation which is easy to read ,and much smaller in size than the older bit-stream look .
Here ,the run-length compression is used to transform 1's and 0's into this string ,so that it's much smaller to represent into a program ,and easier to draw on screen .

-So ,let's continue digging into the code ,let's look into the other for loop ,its header has only a condition part ,which is ( a-- > 64 ) ,which is easily makes the second for loop iterates N times ,where ( N = ord(a) - 64 )* ,inside the for loop ,we can see the putchar() function which prints the code out on screen ,it has a little condition ,which prints either a space character ,or an exclamation mark character :
++c=='Z' ? c = c/ 9:33^b&1
 it's a ternary operator statement ,which acts like a branching statement ,if c is equal to 90 ( decimal representation for 'Z' ASCII character ) ,then it will return c to 10 as it was and prints it ( 10 is the decimal representation for the new line feed ASCII character '\n' ) ,if not ( less than 90 ) ,it will execute that weird equation ( 33^b&1 ) ,what this equation really does is too simple ,if (b) is even number ,it will print 33 on screen ( decimal representation for '!' ASCII character ) ,if (b) is odd ,it will decrement one and print 32 on screen ( decimal representation for space ' ' ASCII character ) .

The explanation of this equation is too easy ,if any character ( group of bits ) is AND'ed ( bitwise AND operation ) with the digit 1 ,the result will be the least significant bit of that input character ( also known as bit masking operation ),so here if b&1 gave 1 ,it means that the LSB of b is 1, which means that b is an odd number ,and if it gave 0 ,it means that the LSB of b is 0 ,which means that b is an even number ,after that ,it XOR's the result with 33 ,we know that any bit XOR'ed with zero ,will give the same inputed bit ,that means that if the result of the masking operation ( b&1 ) was zero ,that means that the LSB of b is zero ,which means that 33 won't change and it will be printed as is on screen ,and if the result of the masking operation  was one ,that means that the LSB of b is one ,which means that 1 XOR 1 = zero ,which decrements one from 33 and becomes 32 and printed as a white space on screen .

And voilà ,the code just decodes every character in the string of the first loop ,and prints the bitmap on screen using '!' and white space characters ,forming that beautiful map figure we see .

The application can be written in a lot easier way than the above form :


Note that i have tried to make the code as easy as possible ,if you have a more easier implementation ,just drop a comment here or send me a private message with your code .

Finally ,i hope that this analysis is helpful for anyone interested in programming in C and learning different ways of coding .

Notes :

*As i mentioned in the very beginning of this post ,i used python while analyzing this C program ,for those who aren't familiar with Python ,ord() is a built-in method in python 2.7x that takes an ASCII character ,and returns its decimal equivalent .

Wednesday, August 7, 2013

Facebook ,Going Stealth ,Seen no more

Hello Folks ,

Today ,we will be hanging around for a little trick in *hacking* ,actually that might be interesting for most people who need to hide their tracing's along the world wide web chat communities .

Our main purpose will be hiding the "Seen" functionality in the most famous social networking site ,Facebook ,so let's seek some anonymity .

So ,first of all ,let's analyze the "Seen" functionality to see how it works ,and then trying to figure a way out to bypass it .

Analysis Phase :

-When you chat with someone using facebook messaging system ,you are actually sending and receiving a lot of authentication in a TCP form hand shaking(s) ,actually these connections are sent via HTTP POST method requests ,that way ,everything will be sent in data part of the request not in the visible section of the URI .

Using Tamper Data* ,we sniffed some traffic ,until an interesting packet appeared .

As we noticed ,the connection is made to the file (/ajax/mercury/change_read_status.php) ,which ,as the name shows ,is responsible to check if the message is read or not ( by focusing your cursor on the chat box of the conversation ),and if it is ,it triggers the function that's responsible to turn on the "Seen" functionality ,and writes the keyword (Seen) to the other end of the conversation using another mercury file ( /ajax/mercury/mark_seen.php ) ,as showed below .

Notice that the (mark_seen.php) script is only triggered in your side when you send messages ,so it waits a signal from (change_read_status.php) script from the other side(s) of the conversation and marks it as Seen message when it receives the signal ,while if you are the receiver ,by clicking the chat box and focusing your cursor on the conversation bar ,that way you are triggering the (change_read_status.php) script and sending a signal to the other end point ,so it can know that you really read the latest message sent to you .

So ,if we got a way here to just mess around with this authentication traffic ,using a way or another to be able NOT to trigger the call in the (change_read_status.php) script ,that way we might be able to see messages ,without the other part of the conversation to see the (Seen) keyword in their chat ,and thus ,thinking that the message is still pending and not read yet .

Going stealthy :
-Do you know that you can bypass this mechanism ,without installing any third party application for your browser ?
Actually ,that wasn't a joke !
Thinking about it ,it's a lot easier than you might imagine ,you can simply bypass this by only blocking the requests going to the (change_read_status.php) file ,thus ,on the other side(s) of the conversation ,the (mark_seen.php) script will never receive your signal ,and your friend(s) will never know that you really read your message ( unless they are actually sitting next to you !!! ) .

Finally ,of course that's not a full tutorial on " how to hack facebook " or " step by step into social anonymity " ,it's just an article that discusses a feature ( well ,maybe for some people and for some reasons ,it may not be ) ,and how to bypass it with minimal use of applications ( as you may have already noticed ,we bypassed it without using any extension or a third party application ,just a browser ,and a human with a working brain ) .

Many thanks to Marwan Rashad for choosing a perfect title for this article :-) .

References :

*Tamper Data : You can download this tool for mozilla browsers ,from  for free .

Tuesday, July 9, 2013

All your free tools belong to us

Hello Guys ,

After publishing my last article, I thought it might be necessary to publish a special article about tools used in programming, development, reversing, penetration testing, so that any future article won't contain a direct link to the tools used inside, instead, I'm going to link this article as a reference.

Important Notes :
-If anyone have any suggestion/comment, feel free to contact me on:
secmania{at}hotmail{dot}com .
-All tools shared in here, are totally free.

Virtualization environment:

  • Vmware Player: A Virtualization tool used to simulate most OS.
  • Oracle Virtual Box: A Virtualization tool that works under GNU/GPL v2 License.
  • Qemu: A Intel x86 machine emulator.
Operating Systems:
  • Linux Kernel: A free, fast and secure Kernel.
  • BackTrack: A free penetration testing linux distro.
  • Knoppix: A live recovery linux distro.
  • ReactOS: A free, open source operating system based on Microsoft Windows NT architecture and compatible with windows drivers and applications.
  • OpenSolaris: A free, fast and stable OS made by Sun Microsystems.
  • JNode: A free OS almost written in Java.
  • Vim: A free, powerful command line text editor.
  • GNU Nano: A free, powerful command line text editor.
  • Notepad++: A free and powerful text editing tool for windows OS.
  • Bluefish: A free, open source and powerful text editor.
  • GNU Emacs: A free, open source and powerful text editor. 
  • Free Hex Editor: A free hex editor.
  • RTA: Hex and Assembly editor. 

Interpreted Languages:
Compiled Languages:
  • C Compilers:
  1. GCC
  2. LCC
  3. Bloodshed Dev-c++
  4. Borland Turbo C++
  • Java IDE's:
  1. Eclipse 
  2. Oracle Netbeans 
  3. JetBrains IntelliJ IDEA
  • Pascal Compilers:
  1. FreePascal
  2. GNU Pascal
  • C Sharp Compilers:
  1. ccompiler
  2. CSharp Mono
  • GAS: Linux GNU assembler.
  • NASM: Netwide assembler.
  • TASM: Turbo assembler.
  • FASM: Flat assembler.
  • ld : GNU Linker.

Web Server-side Languages:

Web Servers:
 Debuggers and disassemblers:
 Penetration testing Frameworks:
Network and web application penetration tools:
  • Burpsuite: Web application penetration testing tool.
  • Tor: Anonymous browser.
  • Scapy: Packets creating ,manipulating and editing tool.
  • Aircrack-ng: Wireless WEP/WAP-PSK 802.11 cracking tool.
  • Paros: Web application proxy tool.
  • Ettercap: Network packets sniffer tool.
  • TCPDump: Packet analyzer tool.
  • Kismet: Wireless sniffing tool.
  • Nessus: Web application and services auditing and pentesting tool.
  • Netcat: Network traffic intercepting tool using TCP/IP protocol.
  • Nmap: Network scanner tool.
  • Cain & Abel: Password recovery and network traffic intercepting tool.
  • Ethreal: Protocol development and troubleshooting tool.
  • Wireshark: Network protocol analyzer tool.
  • OpenVPN: VPN creation and connection tool.
Encryption tools:
Memory Analysers and Reverse Engineering tools:
Miscellaneous tools:

Happy Hunting.


Thursday, June 27, 2013

Manual UPX Unpacking of binary files

Hey guys ,

Here comes a new technical post after a 4-month delay  ,and some rough political issues in here !

Anyway ,in this post we are going to discuss one of the most important tools that must be known for any reverse engineering hacker or binary analyst professional ,technically named UPX unpacking ,unlike famous unpacking tools nowadays people using ,we are going to manually unpack a UPX packed binary image .

First of all ,what is UPX ?

UPX ,abbreviation of the Ultimate Packing for eXecutables ,is a packing tool for binary files ,used to compress data inside a file ,and automatically decompress it when executing the file ,that way of obfuscation of data helps malware hackers to trick in-memory scanning applications ( AV's ,anti-spyware's ,etc... ) ,so that they won't find in a direct way ,the malicious signature of the malware ,before actually executing it .

Technically ,in the packing step ,UPX compresses every section of the binary file ( such as .text , .bss sections ) ,and renames them to sequential blocks UPX0 ,UPX1 and so on ,and then it appends a block of code in the end of the code section of the file ,that decompresses each section and fixes the IAT when executing the file ,and finally ,it changes the OEP of the real binary file to the new decompressing code block appended in the end of the code section .

In the unpacking step ,the following scenario takes place :
-First ,It saves the values of all GPR's and status flags by pushing them into the stack ( most probably ,using a PUSHAD instruction )
-Then ,It starts decompressing the packed blocks ( UPX0 ,UPX1 ,... ) ,and saves them into memory .
-It then fixes the IAT of the real unpacked binary .
-Finally ,it restores saved GPR's and flags ( most probably ,using a POPAD instruction ) ,and redirects the flow to the real OEP .

Well ,honestly ,this is one of the simplest kinds of in-memory executable packing ,some other packers use custom compressing algorithms ( or even a custom UPX packing scheme ) ,and sometimes ,UPX packing doesn't unpack bytes in-place ,it might use a temporary file to unpack the real executable at .

To clarify the picture a bit ,I'm going to show a real world study case ,we will step from unpacking ,until getting the full real executable ,manually !

Tools :
-PEid ,to just be sure that our executable is detected as a UPX packed binary file.
-Immunity Debugger ,or any other debugger you prefer working with .
-UPX ,the official UPX packing tool .
-Import reconstructor ,a great (really!) IAT fixing tool .

Note: Import Reconstructor is used because the fact that we are going to manually unpack our binary file ,so we will make each step the unpacker does to decompress the file ,including the IAT fixing step .

Scenario :
First of all ,we will make our own simple executable ,here ,i prefer to make a simple one ,so i made this simple C application :

Compile ,link ,and take the binary executable aside ,that will be our *real* executable file .
First ,let's note some info about it ,we will first load it into PEid ,to make sure about some stuff .

We can notice some important stuff ,first ,it's not a packed binary ,it was compiled in Dev-C++ 4.9.x and linker version is 2.56 ,with the file size and RVA entry address .
Hanging around with PEid ,we can reveal more important information .

Here ,we can see all the binary image sections ,their relative virtual addresses and offsets .

Note that if the file was packed ,we should see UPX0 ,UPX1 ,UPX2 ,and so on ,instead of the real sections .

Here ,there are a lot of information to notice ,first ,our real OEP is 0x401220 ( Flat model physical address ) ,we can also notice the number of sections ,as well as the base address of the code and data sections ,also we can see here the base RVA of the IAT ,if we took a look at the libraries it loads ,we will find that it loads 2 dynamic libraries ,which are Kernel32 and msvcrt ,it loads from Kernel32 the following functions :
AddAtomA() ,FindAtomA() ,GetAtomNameA() ,SetUnhandledExceptionFilter() ,ExitProcess()
and from msvcrt the following functions :
__getmainargs() , __p__environ() ,__p__fmode() , __set_app_type() ,_cexit() , _iob() , _onexit() , _setmode() , abort() ,atexit() , fflush() ,fprintf() , free() ,malloc() ,printf() ,scanf() ,signal()

So ,as shown ,we can see all the functions used in our executable by system's kernel ,so that it operates the way it should .

Here ,we must notice the real entry point of our binary image ,let's just take the first 4 instructions :

SUB ESP, 00000008H
MOV [ESP], 00000001H

So ,now let's start the packing process ,we are going to use UPX official free tool ,to pack our executable ,and we will output the file as upx_calc.exe ,and packing it using this simple command :

Now ,we have a packed binary ,let's try to load it into PEid again ,and see the difference .

We can notice various things here ,first ,it didn't recognize what compiler is used to compile this binary file ,also the OEP has changed .

If we saw the sections of our new binary ,we will notice that the sections have been packed and renamed to UPX0 ,UPX1 ,UPX2 blocks .

 Also ,the IAT has been changed ,now ,it loads the following functions from Kernel32 library :
LoadLibraryA() ,GetProcAddress() ,ExitProcess() ,VirtualFree() ,VirtualAlloc() ,VirtualProtect()

msvcrt library changed to only load the _iob() function .

So ,we can notice here that a lot of stuff changed compared to our real executable ,now let's start unpacking it manually using the lovely immunity debugger .

First ,we launch our upx_calc.exe binary file from within the debugger .

As we can see here ,the OEP is not the same as our old unpacked executable file .
Starting the unpacking routine ,we notice that the very first byte here is a PUSHAD byte ,which as mentioned before ,saves all current GPR's status as well as flags into stack ,stepping over this instruction let us see the stack pointer decremented by the size of the pushed pointers .

From the push instruction on ,we can see the unpacking routines ,and how compressed sections are being decoded and written into the memory ,i won't discuss this algorithm ,as there are a lot of resources on the internet ,and it's out of this article main topic ,so i will concentrate on unpacking the executable only .

Now ,let's find the POPAD instruction ( since it used PUSHAD to save registers ) ,it's opcode is 0x61 .

As we can see here ,after POPAD ,all registers will return to their default values as when we launched the application ,stepping over ,the LEA copies pointer to the address RVA 0xFF44 of the stack to EAX ,so now EAX points to the same as this stack pointer points to ( full physical memory address 0x22FF44 ) ,stepping over again ,we can see this little routine :

JNZ SHORT upx_calc.0040794A

 This routine ,just fills the stack with zeros ,as long as the Zero flag isn't set ( which means that the pointer EAX is not yet equal to pointer ESP ) ,and we already know ( because of the previous LEA instruction ) that this routine will stop when the stack is filled with 0x80 * 4 bytes of zero's ,after this routine ,0x80 bytes will be removed from the stack ( the zero's ) ,and the stack will point to 0xFF44 - 0x80 .

Now ,if we stepped into the JMP 00401220 instruction ,we will land on our real old executable OEP !

All we have to do now ,is just start the application ,and it should start our normal execution flow ,also we can from that address ( the real OEP ) ,dump the data to an external file ,and then use Import Reconstructor to fix the IAT inside the dumped binary image ,so that way ,the dumped binary is our real ,unpacked application ,Voilà .

Today's article ,was a great example ,to start your way into manually unpacking and/or tracing packers' compressing algorithms ,it's also a prerequisite article for the next articles which is going to talk about DLL injection and how to get a file-less code execution into the victim's computer .


References :
[-] UPX Wikipedia :
[-] Security Xploded site articles :

Sunday, February 10, 2013

All your Facebook Worms are belong to us !

Hello guys,

It's my first post after a while of being offline ,hopefully to be worth the delay .

A couple of days ago ,while i was surfing facebook pages ,one of my friends posted about 2 ~ 5 successful posts on my wall .They weren't some usual games/apps links ,they were a url to an external link to some kind of spamming pages ( humm .. unusual ) .
My friend -whom using Chrome browser- did some fuzzing on that site ,and found that ,when somebody clicks that link ,it takes the victim to an external site ,that site is in turkish language and has a button inside ,which when clicked ,downloads and installs automatically a Chrome's extension which in turn makes use of all user data gathered ,and makes use of the facebook account by spreading his worm worldwide .

So now ,a lot of questions can be asked here :
-What is that site ?
-How is it able to take advantage of my facebook account ( or other data ) ?
-What kind of data can be gathered by this worm ?

All these questions can be answered after doing a tiny analysis on the process and steps of this worm .

First of all, let's start by doing the same steps of a user who is going to click on that link ,the shared url is :

When we click on that url ,we are taken to a page that looks like this :

Weird enough !!
The story starts when clicking on that button ( Guncelle ) .When looking into the source code of this page ,we will find that this whole page is just an iframe ,which underneath exists the real malicious site which is :


When clicking on that *virtual* button ,we are actually triggering this javascript code :

var is_opera=navigator.userAgent.toLowerCase().indexOf("opera")>-1;
var is_chrome=navigator.userAgent.toLowerCase().indexOf("chrome")>-1;
var is_safari=navigator.userAgent.toLowerCase().indexOf("safari")>-1;
var is_firefox=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;
else if(is_firefox)
else if(is_opera)
    var inst=""
function go()
What this code actually does is simply ,checking on what browser the victim is surfing the page on ,by checking the SIP userAgent header ,and after that it redirects the user to the valid page based on his browser .

Here ,and because my friend was running chrome ,it will redirect us to :

 This page contains a javascript function named kur() which is defined as follows :
function kur(){
var is_chrome=navigator.userAgent.toLowerCase().indexOf("chrome")>-1;
        alert("Birazdan Çikan Pencerede Ekle Butonuna Tiklayiniz!");
else {
 Again ,it's checking if the victim is running Chrome ,if no it redirects him back to the index page which is the main site running beyond the iframe ,which in turn will see what browser is he running from and redirects him to the valid page ,otherwise ,it executes chrome.webstore.install() function .

So what does this function mean ?! As Chrome's developers page shows :

Once you've published your app or extension, you may be wondering how users will find and install your app. For users who browse the Chrome Web Store and find your item, its a very easy one-click process to install it. However, if a user is already on your site, it can be cumbersome for them to complete the installation - they would need to navigate away from your site to the store, complete the install process, and then return.
As of Google Chrome 15, you can initiate app and extensions installations "inline" from your site. These apps and extensions are still hosted in the Chrome Web Store, but users no longer have to leave your site to install them.
When users install the app, they will see an installation confirmation dialog similar to the one pictured above .Just like the dialog displayed when installing directly from the Chrome Web Store, it lists all of the permissions that your app or extension is requesting. Additionally, this dialog includes the average Chrome Web Store rating and the number of users, giving users extra confidence about what they are about to install.
 The prototype of this inline function looks like this :
chrome.webstore.install(url, successCallback, failureCallback)
It's similar to a "google api" for web applications .It takes three parameters ,we will concentrate on the most important one which is the url from which the function will get the application from .Now when we return to kur() function , we can notice that it's getting an application named : Live Broadcast ,which can do the following as its main webstore page details :
This extension can access:
  • Your data on all websites
  • Data you copy and paste
  • Settings that specify whether websites can use features such as cookies, JavaScript, and plug-ins
  • Your browsing history
  • Your list of installed apps, extensions, and themes
  • Your tabs and browsing activity
So ,continuing with the function kur() ,after getting the application from google web store ,it will use a javascript function named alert() which pops up a message box and then asks the user if he wants to add Live Broadcast extension for Chrome or not via chrome.webstore.install() function .The trick is that it will stay calling kur() function recursively every time the user closes the alert message box and again the extension confirmation box will still pop up until the user accepts it .

And that way ,the worm works and can let the hacker make use of the data anyhow he wants .

It's too dangerous to click on any link you see ,specially from unknow senders or at social sites ,make sure that you know what you are clicking on ,as well as whom sent it before actually clicking on it.

[~]Special thanks go to Eyad Warraky for discovering the worm ,as well as letting me do this beautiful worm analysis ,Thx  ;-)