Friday, February 7, 2014

Android Malware Detecting Emulator

Introduction :
Android is everywhere Phones Tablets. TVs and set-top boxes powered by Google TV. Soon, Android will be in cars and all sort of other places as well. However, the general theme of Android devices will be smaller screens and/or no hardware keyboard. And, by the numbers, Android will probably be associated mostly with smart phones for the foreseeable future. For developers, this has both benefits and drawbacks, as described next.
Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and is growing fast. Every day another million user’s power up their Android devices for the first time and start looking for apps, games, and other digital content. Android gives you everything you need to build best-in-class app experiences. It gives you a single application model that lets you deploy your apps broadly to hundreds of millions of users across a wide range of devices from phones to tablets and beyond. As with increase in popularity of this platform it has become attractive target for the hackers. Attackers have shifted their interest to this platform because it not only gives access to victim’s files and personal details but also gives information regarding victim’s location. Attackers can intercept victim’s phone calls and messages.
Android malicious  program  also capable to detect if they are running in emulator, this information can be very useful to malware author, lets see how, suppose you are a malware author and you don’t want you malware to  be detected by antivirus program, but it some how catches suspicion of some malware analyst and out of curiosity he runs it on emulator and he is all full of information which is radiated by your malware program on network and all other sort of communication medium. Malware analyst use sandboxes and analysis framework to detect malicious program infact even prior publish your app on Google play store it Scan your app with Google Bouncer, It is mainly based on Dynamic analysis which means it will observe behavior of you app while it is running and this is done on an emulated environment. I haven’t tried this code on Google Bouncer program.  But what a smart malicious program will do is, if they detect that they are running on emulator they will behave well manned no stealing credentials, no logging keystrokes, etc i.e. they will behave like a normal application what they look like non-malicious and escape this detection program or the person trying to prove the app guilty. In this post will show you how we can do this using API provide by android official SDK no low level hack. Simple and straight.
Meet The C0d3s :
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

            @Override
protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
TelephonyManager tManager = TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            String uid = tManager.getDeviceId();
            TextView tv=(TextView) findViewById(R.id.code);
            if(uid.compareTo("000000000000000")==0)
                        {Toast.makeText(this, "Runn!ng 0n 3mul4t0r", Toast.LENGTH_LONG).show();
                        tv.setText("Runn!ng 0n 3mul4t0r");

//Behave yourself (Run non-malicious code stay calm)
                        }
            else
                        {
                                    Toast.makeText(this, "Runn!ng 0n  "+uid, Toast.LENGTH_LONG).show();
                                    tv.setText("Runn!ng 0n Ph0n3");
//Run real malware program
                        }
}
}

What is does ?
We get the system “Telephoney Service “ which has information about your phone like IMEI no(International Mobile Equipment Identity) this is exactly what we need, Every cell phone on this earth is assigned a unique 14 digits to identify them uniquely, Since on emulator there will be no such no if it return zero will can say we are running on emulator or if we get real digits then hell yeah ! we are running on phone

Meet The 0utput:


Running on Phone


Running On Emulator

Tuesday, August 27, 2013

Anti Debugging Trick

Anti-debugging is a popular anti-analysis technique used by malware to recognize when it is under the control of a debugger or to thwart debuggers. Malware authors know that malware analysts use debuggers to figure out how malware operates, and the authors use anti-debugging techniques in an attempt to slow down the analyst as much as possible. Once malware realizes that it is running in a debugger, it may alter its normal code execution path or modify the code to cause a crash, thus interfering with the analysts’ attempts to understand it, and adding time and additional overhead to their efforts. There are many anti-debugging techniques—perhaps hundreds of them -  I will discuss only the most popular ones that we have encountered in the real world cover as much I can and also show some sophisticated one also and also how to defeat the while debugging session I will use python scripting with immunity debugger to defeat the tricks if you don’t about python scripting with immunity debugger the visit  this might help you ;) . But first lets start with the most simplest and  basic one with uses Windows API -

IsDebuggerPresent() :

By far the most common anti-debugging technique is to use the IsDebugger- Present function exported from kernel32.dll. This function call takes no parameters and returns 1 if there is a debugger attached to the current process or 0 if there isn’t. If we disassemble this function, we see the following assembly:

7C813093 >/$ 64:A1 18000000 MOV EAX,DWORD PTR FS:[18]
7C813099 |. 8B40 30 MOV EAX,DWORD PTR DS:[EAX+30]
7C81309C |. 0FB640 02 MOVZX EAX,BYTE PTR DS:[EAX+2]
7C8130A0 \. C3 RETN

This code is loading the address of the Thread Information Block (TIB), which is always located at offset 0x18 from the FS register. From there it loads the Process Environment Block (PEB), which is always located at
offset 0x30 in the TIB. The third instruction is setting EAX to the value of the BeingDebugged member in the PEB, which is at offset 0x2 in the PEB. If there is a debugger attached to the process, this byte will be set to 0x1. A simple bypass for this was posted by Damian Gomez of Immunity, and this is one line of Python that can be contained in a PyCommand or executed from the Python shell in Immunity Debugger:

imm.writeMemory( imm.getPEBaddress() + 0x2, "\x00" )

This code simply zeros out the BeingDebugged flag in the PEB, and now any malware that uses this check will be tricked into thinking there isn’t a debugger attached .


Saturday, August 24, 2013

Breaking Single Character XOR Cipher



Of course this been topic cryptography I wouldn’t bug you up with whole lot of complicated mathematic. Single character XOR cipher been the most simplest and effective encoding technique used by malware author for exfiltration of data and it is used very often. For those who are not familiar with this term, exfiltration data files contains stolen data from victims computer and it resides on victims computer and the malware will export it to Command and Control center eventually. Another reason using such simple technique instead of algorithms such as Blowfish or AES-256, is it might trigger IDS or IPS single character XOR inspite of been simple it does gives sufficient level of obfuscation.

Now talking about Single Character XOR cipher, the data to encode is XOR with one byte key this will yield cipher text. For ex
To encode the data :
DATA  Key = Cipher text
  5Fh   
54h = 0Bh
To decode the data :
 Cipher text Key = DATA
  0B   
54h = 5Fh
But our goal is to break Ciphertext and to recover the   key which help us to recover the original data. The tool we will be using are :
1.   A hex editor   
Now talking about the algorithm we will use :
We will simply assume a key the XOR the data to recover the plain text now we will search for occurrence of most frequently occurring English words some method for "scoring" a piece of English plaintext. (Character frequency is a good metric.) Evaluate each output and choose the one with the best score. if we get the word then bingo we got the key. If not try other key since the range of key is from 0 to 255(FFh) i.e one byte it is abe piece of cake for a computers of this era.

This is the encoded data which we will crack:



 After XOR with X (0x58) we will get :



Taking the top 100 most commonly used English word we can do this attack first we will put the XOR logic in a loop which iterate the key from 0(0x0) to 255(0xFF) on each iteration we will compare the decoded data to our list of 100 frequently occurring English if we have the occurrence  we will print it .

The script is as follows :

import binascii,sys
keywords=['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after', 'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give', 'day', 'most', 'us']
def inc_key(key):
    int_key=int(key,16)
    int_key=int_key+1
    hex_key=hex(int_key)[2:]
    return hex_key

def decrypt(data,key):
    xor=lambda x ,y :int(x,16)^int(y,16)
    ans=""
    for temp in [data[a:a+2] for a in range(0,len(data)-2,2)]:
        ans=ans+chr(xor(temp,key))
       
       
    return ans
       

def body(data):
   
    key="00"

    for a in range(0,255):
        ans=decrypt(data,key)
        for word in keywords:
            word=" "+word+" "
            if word in ans or word+" " in ans or " "+word in ans or " "+word+" " in ans:
                print "[*]Encrypted data : "+data
                print "[*]Decrypted data : "+ans
                print "[*]key : 0x"+(key)
                break
        key=inc_key(key)


if(len(sys.argv)==1):
        print "\tuseage :\n\t"+sys.argv[0]+" <file name>"

if(len(sys.argv)==2):
          print "[+]Starting Decrpytion ..."
          for data in open(sys.argv[1]):
                   body(data)

          print "[+] Done





It should also be noted that this technique is useful in extracting malware from antivirus quarantines. Frequently, intrusion analysts are only called in after a first responder already tried to fix the problem. The “fix” may include installing an antivirus program that captures and encrypts valuable evidence. If the only copy of malware that you need to analyze is located in a quarantine container, then consider what methodologies may have been used to lock them inside. For example, simply unzipping McAfee quarantine files with 7-zip and reversing the files with the XOR key j (hex 0x6A) will yield the original malware.
XOR encryption is used frequently, for both legitimate and illegal purposes; it is important for analysts to know that this encryption can be broken with minimal effort and the result may be very valuable to the investigation.

Thursday, March 14, 2013

Sniffing data before its gets encryted in mozilla https encryption (SSL encryption)


I will demonstrate how to use immunity python scripting to sniffing encrypted traffic at the application layer(if you new to this topice then please refer to this post  ). Normally to understand how a client or server application interacts with the network, we would use a traffic analyzer like Wireshark. Unfortunately, Wireshark is limited in that it can only see the data post encryption, which obfuscates the true nature of the protocol we are studying. Using a soft hooking technique, we can trap the data before it is encrypted and trap it again after it has been received and decrypted. Our target application will be the popular open-source web browser Mozilla Firefox.  For this tutorial we are going to pretend that Firefox is closed source otherwise it wouldn’t be much fun now, ;) and that it is our job to sniff data out of the firefox.exe process before it is encrypted and sent to a server. The most common form of encryption that Firefox performs is Secure Sockets Layer (SSL) encryption, so we’ll choose that as the main target for our tutorial.

There is no “right” spot to place your hook; it is really just a matter of preference. Our  Hook point is on the function PR_Write, which is exported from nspr4.dll. When this function is hit, there is a pointer to an ASCII character array located at [ ESP + 8 ] that contains the data we are submitting before it has been encrypted. That +8 offset from ESP tells us that it is the second parameter passed to the PR_Write function that we are interested in. It is here that we will trap the ASCII data, log it, and continue the process. First let’s verify that we can actually see the data we are interested in. Open the Firefox web browser, and navigate to one of my favorite sites, https://www.facebook.com/. Once you have accepted the site’s SSL certificate and the page has loaded, attach Immunity Debugger to the firefox.exe process and set a breakpoint on nspr4.PR_Write. In the top-right corner of the facebook website is a login form; set a username to test and a password to test and click the Login button. The breakpoint you set should be hit almost immediately;
keep pressing F9 and you’ll continually see the breakpoint being hit.

Script :

from immlib import *

class fire (LogBpHook) :
          def __init__(self):
                   self.imm=Debugger();
                   self.logfile = "D:\\fire_log.txt"
#directory where the log file has to be saved
                   LogBpHook.__init__(self)
                  
          def run(self,regs):
                   addr=self.imm.readLong(regs['ESP']+8)
                   str=self.imm.readString(addr)
                   self.imm.log("PR_Write ( 0x%x) <- %s" % (addr,str) )
                   fd = open( self.logfile, "a" )
                   fd.write( str )
                   fd.close()
# this function run automatically when hook is hit and function code is #executed which logs it in to file and displays on log window of debugger
                  
def main(args) :
          imm=Debugger()
          wfun=imm.getAddress("nspr4.PR_Write")
#setup hook point
          fire_hook=fire()
          fire_hook.add( "%08x" % wfun, wfun)
          return "[*] READY for ACTION"


How do I run it ??

1.   Save the above file with .py extension (firehack.py) ;) …. As it is python file . then copy it in immunity install directory
2.   Then type !<filename> (without .py extension for eg !firehack)
3.   All the encrypted traffic will to shown on log window of immunity debugger and also logged in the file
4.   To find user id and password just do a search in file “username” , “password”,”passwed”,”email” different website use different name facebook uses “email”.

This way we can sniff the data in application before it gets encrypted it can save a lot of reverse engineering time . Such scripting tools can save considerable time in malware analysis , exploit development as reverse engineers task are automated

Immunity debugger and support for Python scripting


Immunity Debugger is a powerful new way to write exploits, analyze malware, and reverse engineer binary files. It builds on a solid user interface with function graphing, the industry's first heap analysis tool built specifically for heap creation, and a large and well supported Python API for easy extensibility.
Immunity Debugger's interfaces include the GUI and a command line. The command line is always available at the bottom of the GUI. It allows the user to type shortcuts as if they were in a typical text-based debugger, such as WinDBG or GDB. Immunity has implemented aliases to ensure that your WinDBG users do not have to be retrained and will get the full productivity boost that comes from the best debugger interface on the market.
Features :
1)  A debugger with functionality designed specifically for the security industry
2) Cuts exploit development time by 50%
3) Simple, understandable interfaces
4) Robust and powerful scripting language for automating intelligent debugging
5) Lightweight and fast debugging to prevent corruption during complex analysis
6) Connectivity to fuzzers and exploit development tools
7) The Python API ("Immlib/Lib reference" for full documentation)
8) A full Python based graphing library
9) Full debugger and GUI API access
10) A flurry of cool example scripts such as:
- !heap         A fully working heap dumping script (try the -d option!)
- !searchheap   Searching the heap
- !hippie       Trampoline hooks on RtlAllocateheap/RtlFreeHeap
- !modptr       Dynamic search for function pointers in pages
- !findantidep  Find address to bypass software DEP
Interface: Commands can be extended in Python as well, or run from the menu-bar. Python commands can also be run directly from our Command Bar. Users can go back to previously entered commands, or just click in the dropdown menu and see all the recently used commands.
Remote command bar : From the command line menu, you can choose to start a threaded command line server. so you can debug remotely from another computer.
Built in Graphing
Another Immunity Debugger feature is the capability of creating function graphs. Our Python VCG library will create a window inside Immunity Debugger at the click of a button to graph your selected function. No third party software is required.
Immunity Debugger is light
Immunity Debugger strives to absorb as few resources on the system as possible. Being too CPU-heavy will cause heap overflows and other complex vulnerabilities to behave differently than they would under normal load. Likewise, fuzzing and other vulnerability analysis is only possible when the debugger is not causing undue system strain.
Immunity Debugger exposes the information you need
Most debuggers offer only one method to allow you to attach to a process of interest - the pid and the process name. Immunity Debugger offers the pid, process name, services within that process, TCP/UDP ports listened to by that process, complete binary name, and window name. This allows quick and easy access to the exact process you wish to analyze.
Python Scripting : Python scripts can be loaded and modified during runtime. The included Python interpreter will load any changes to your custom scripts on the fly. Sample scripts are included, as is full documentation on how to create your own. Immunity Debugger's Python API includes many useful utilities and functions. Your scripts can be as integrated into the debugger as the native code. This means your code can create custom tables, graphs, and interfaces of all sorts that remain within the Immunity Debugger user experience. For example, when the Immunity SafeSEH script runs, it outputs the results into a table within the Immunity Debugger window. Other scripts can ask for user input with dialogs and combo boxes.Having a fully integrated Python scripting engine means you can easily paint variable sizes and track variable usage, which in turn comes in handy when trying to automatically find bugs!
Python Hooks
Often you will want to run a Python script on certain program events, for example when a breakpoint is hit or an exception is caused. Immunity Debugger hook support includes many debugger events, and more are added with every release.

Python Hooks : Often you will want to run a Python script on certain program events, for example when a breakpoint is hit or an exception is caused. Immunity Debugger hook support includes many debugger events, and more are added with every release.
Immunity Debugger ships with 13 different flavors of hooks, each of which you can implement as either a standalone script or inside a PyCommand at runtime. The following hook types can be used:
BpHook/LogBpHook : When a breakpoint is encountered, these types of hooks can be called. Both hook types behave the same way, except that when a BpHook is encountered it actually stops debuggee execution, whereas the LogBpHook continues execution after the hook is hit.
AllExceptHookAny exception that occurs in the process will trigger the execution of this hook type.
PostAnalysisHook : After the debugger has finished analyzing a loaded module, this hook type is triggered. This can be useful if you have some static-analysis tasks you want to occur automatically once the analysis is finished. It is important to note that a module (including the primary executable) needs to be analyzed before you can decode functions and basic blocks using immlib.
AccessViolationHook : This hook type is triggered whenever an access violation occurs; it is most useful for trapping information automatically during a fuzzing run.
LoadDLLHook/UnloadDLLHook : This hook type is triggered whenever a DLL is loaded or unloaded.
CreateThreadHook/ExitThreadHook : This hook type is triggered whenever a new thread is created or destroyed.
CreateProcessHook/ExitProcessHook : This hook type is triggered when the target process is started or exited.
FastLogHook/STDCALLFastLogHook :These two types of hooks use an assembly stub to transfer execution to a small body of hook code that can log a specific register value or memory location at hook time. These types of hooks are useful for hooking frequently called functions