Posts Tagged ‘malware’

Volatility VS Citadel

As a forensic and malware analyst, I have always been a big fan of Volatility, the Python coded memory analysis tool that keeps growing day by day. Thus, since I readed the Michael Ligh’s article on his blog about the extraction of the ZeuS’ encryption keys, I was willing to try out the same thing with another malware family as well.

I’ve chosen Citadel in this case, that is one of the most widely used ZeuS’s variants since its source code leakage. Specifically the version that, while not the last one, will be the basis for subsequent versions (although it is rumored that could be the last we see) or other families.

When using Volatillity and Yara together, the power available for automatic malware processing increases. “zeusscan2“, one of the plugins resulting from the article mentioned above, is based on both things. It makes use of Yara rules against an infected machine’s memory to detect and access those memory regions that likely contains the information we want to extract from the binary file. This requires a thorough analysis on the family prior to “automate”, which in this case, being a variant of the well known and documented Zeus family, the work is limited to detecting differences within it.

As a start point, we know that ZeuS 2.X contains the following information embedded in the binary:

  • Initial config file download URL
  • RC4 key used to decipher the config file
  • Info about the location of the binary and his config on the infected machine

The first two can be found within the binary in a XOR encoded area with the bytes at the beginning of the last PE section, while the latter is an encrypted area using the RC4 key and with a fixed structure (For now on we will refer to it as the “magic object” to follow the convention used in the Volatility’s ZeuS plugin).

Note: In ZeuS’ case there’s a second RC4 encryption key contained in the last commented structure, but since Citadel lacks of it, is not relevant to the purpose of the article.

Thereby, the processing and extraction flow we are searching for should be something like:

  1. Embedded config finding.
  2. XORing with the bytes at the beginning of the last PE section to decode it.
  3. RC4 key and initial config file download URL extraction.
  4. Searching and decoding of the “magic object”
  5. Rest of data extraction

Now that we know the base which supports Citadel, we can study the differences to adapt the plugin to the new family. The similarities (at binary level at least) are bigger than the differences, so once we understand it, the changes are not complicated.

The main difference comes from the cipher algorithm used to encrypt the downloaded config files (AES instead of RC4), but the “magic object” keeps RC4. The AES key, it’s not within the binary as so, but it’s calculated on runtime in the following way:


The BO_LOGIN_KEY or binary key, is a 16 hexadecimal bytes key that can be found inside the binary and, in addition to compute the AES key, it’s used in the control panel communication, so to the localization of the embedded config and the “magic object”, we must add the hardcoded key.

To the workflow above, it should be added:

  1. BO_LOGIN_KEY finding
  2. AES key computing

With all of this, we can choose the following disassembled code to generate the new Yara rules that help us to find the commented variables in memory:

8BEC                                  MOV EBP,ESP

83EC 0C                             SUB ESP,0C

8A82 00010000                  MOV AL,BYTE PTR DS:[EDX+100]

8845 FE                              MOV BYTE PTR SS:[EBP-2],AL

8A82 01010000                  MOV AL,BYTE PTR DS:[EDX+101]

8845 FD                             MOV BYTE PTR SS:[EBP-3],AL

8A82 02010000                  MOV AL,BYTE PTR DS:[EDX+102]

B9 801A1300                      MOV ECX,131A80                                                   ; BO_LOGIN_KEY

8845 FF                              MOV BYTE PTR SS:[EBP-1],AL

E8 BEF2FFFF                    CALL 0015BC16


56                                        PUSH ESI

BA 54050000                      MOV EDX,554                                                          ; Embedded configuration length

52                                        PUSH EDX

68 602A4000                       PUSH pyko.00402A60                                             ; Embedded configuration

50                                        PUSH EAX

E8 47E30100                      CALL pyko.004290C1

8B0D B4394300                 MOV ECX,DWORD PTR DS:[4339B4]

030D 943D4300                 ADD ECX,DWORD PTR DS:[433D94]

8BF2                                   MOV ESI,EDX

2BC8                                  SUB ECX,EAX


68 03010000                      PUSH 103

8D85 10FBFFFF               LEA EAX,[LOCAL.316]

50                                       PUSH EAX

8D85 FCFEFFFF              LEA EAX,[LOCAL.65]

50                                       PUSH EAX

E8 B4E20100                     CALL pyko.004290C1

B8 1C010000                     MOV EAX,11C

50                                       PUSH EAX

68 283C4300                     PUSH pyko.00433C28                                               ; Magic object

Once we get to the workflow processing part in which the “magic object” is decoded, we then face to a structure similar to:

This object, like happened with ZeuS 2.X, has a fixed length in most cases and a structure like the following:

{‘_ZEUS_MAGIC’ : [ 0x11C, {

'struct_size' : [ 0x0, ['unsigned int']], \

‘guid’ : [ 0x4, ['array', 0x30, ['unsigned short']]], \

‘guid2′ : [ 0x7C, ['array', 0x10, ['unsigned char']]], \

‘exefile’ : [ 0x9C, ['array', 0x14, ['unsigned char']]], \

‘keyname’ : [ 0xEC, ['array', 0xA, ['unsigned char']]], \

‘value1′ : [ 0xF6, ['array', 0xA, ['unsigned char']]], \

‘value2′ : [ 0x100, ['array', 0xA, ['unsigned char']]], \

‘value3′ : [ 0x10A, ['array', 0xA, ['unsigned char']]], \

‘guid_xor_key’ : [ 0x114, ['unsigned int']], \

‘xorkey’ : [ 0x118, ['unsigned int']], \


So we already have everything we wanted:

I hope this example helps to understand a little better all the capabilities Yara and Volatility offers when automating and analyzing malware.

The plugin for the version can be found here. Michael Ligh has also merged it with the previous versions of the ZeuS 1 & 2.X plugins, so from now on it will be shipped with Volatility too, though it won’t be enabled by default; Use the –plugins parameter to access them like this:

$ python –plugins=contrib/plugins/malware citadelscan1345 -f ….

Regarding version, the process to follow should be similar to the one described, except for a new hardcoded key and the size and structure of the “magic object”, that changes from sample to sample.

Happy analysis!

Follow me on Twitter: @smvicente

MSDN Help Plugin for OllyDbg / Immunity Debugger

Hello everone. Today I’m showing you a new plugin for OllyDbg / Immunuty Debugger that I hope will help you when reversing Windows binaries.

What is OllyDbg?

OllyDbg is a classic user-mode debugger for the Windows operating system. According to many, it’s the idea tool for reverse engineering software when you’re not likely to get a hold of the source code (malware, for example), and it’s also widely used in the cracking scene.

One of its most appealing features is the possibility of loading plugins. While most of them are geared towards binary unpacking and avoiding detection from malicious code, there are plugins readily available for a multitude of tasks.

What is Immunity Debugger?

After many years went by, no updates were available. That meant no fixes for the multiple public exploits available on the Internet. That’s until Immunity decided to buy the source codes to OllyDbg in order to fix and improve it, under the new name Immunity Debugger. Today it seems to be mostly replacing the good old Olly, especially when it comes to exploit development which is where the focus is set for most of the new features and plugins.

So what’s the catch? Well, it turns out most of old Olly’s plugins don’t work anymore. However, if you have their sources you can update them, even make them work in both debuggers. If you don’t things get a bit hairy, although there’s a tool out there that helps quite a lot.
Today’s plugin works correctly under both debuggers, of course. :)

What’s this plugin for?

OllyDbg has been around for some time now, and it’s beginning to show its age. ;) One of it’s low points right now is it’s (rather lack of) Win32 API help support.

I’ll explain. When you’re reversing a binary on Windows you’ll tipically see a bunch of assembly code with Win32 API calls in between. The Win32 API is the low level interface for user-mode applications, so deep down inside, it all boils down to these function calls. There are simply too many of them and it’s impossible to memorize them all, so it’s necessary to consult the Microsoft documentation to know what they do, what arguments they expect, etc.

Now, OllyDbg had always allowed you to consult the documentation thanks to a nifty file called “WIN32.HLP” that was shipped with the SDK for Windows NT, and it contained the most up to date and detailed version… back then. But many OS versions and years went by, Microsoft stopped shipping that file since the new MSDN (Microsoft Developer Network) was all the rage, and what happens now when you try to use the OllyDbg help is that half the times the API you’re looking for doesn’t show up in the help file. :(

This plugin is meant to fill that void. After installing it, when OllyDbg tries to open WIN32.HLP to show the help, the plugin steps in and launches the default web browser instead, pointing it to the corresponding page in MSDN Online. :)

How to install this plugin?

It’s easy, just download the zip file, extract the plugin (OllyMSDN.dll) and copy it to the debugger’s program files folder. For OllyDbg this is tipically “C:Program FilesOllyDbg” and for Immunity Debugger it’s “C:Program FilesImmunity IncImmunity Debugger”.

The next step is to run the debugger, go to the menu “Help” and click on “Select API help file”. Then we have to select the old WIN32.HLP file, or at least any other file as long as it has the exact same name (it’s not going to be used anyway). The name matters because it’s the way the plugin can tell Olly is trying to load the Win32 API help and not just any other help file like, say, the user manual.

Once you’ve done this, the plugin is ready to use.

How to use this plugin?

It’s used just like the good old WIN32.HLP file. That is:

To show the Microsoft documentation, go to the “Help” menu and click on “Open API help file”.

To see the help for an API call in particular, right click on the assembly code line with the function call in the CPU pane and go to “Help on symbolic name”.

Where do I get this plugin?

You can purchase it online with your credit card… nah, no way! It’s 100% free of course! :)

Follow this link to download:

The zip file contains the precompiled Windows binary and the complete source code under GPL v2 license. The sources compile with Visual Studio 2008, I haven’t tried other compilers.

Well, that’s it for today. Enjoy! :)

Follow me on Twitter: @Mario_Vilas | Linkedin:

The ZeuS and Spyeye module for Android keeps growing

In the latest post about the mobile module used by Zeus and SpyEye to attack the second authentication factor, we commented on the small improvement these samples experienced since their inception in September 2010. They must have heard us because we are facing what appears to be the first step in the evolution of malware used so far to merely intercept and forward SMSs to a bot with further possibilities.

First of all you can see how the endless list of permissions requested for installation was abridged with the clear intention of drawing less attention to the victim:

New permissions are now requested for actions such as installing applications or reading the phone book. And instead of a generic affectation, now it has a given bank as a target.

The application pretends to be a bank token system of the target company. Added to the corresponding injections in the victim’s computer, this will provide the necessary social engineering to persuade the user to install it as well as to maintain it. It can still massively capture and forward SMSs, and, moreover, filter them if defined in the XML file used as configuration:

The XML serialization is done using Simple Framework, and one of its most interesting characteristic, besides its new capacity to read and send data from the phone book, is that it seems to be capable of receiving a series of commands, which turns it into a bot:

As for the control panel, it has been substantially improved and remains separated from PC infection controllers, probably because the mobile module is “commercialized” independently:

It also has a builder available to generate specific “APK” against a given bank:

Therefore, behind the “bank module” used so far by other desktop Trojans, we are dealing here with the first signs of major development and possible commercialization, allowed by the introduction of new features with the purpose of achieving some independence. We sincerely hope that the so-called “Zeus for mobiles” does not become a reality and ends up turning exactly into that.

Follow me on Twitter: @smvicente

New sample attacks the second mobile-based authentication factor

In September 2010 the first sign of ZeuS was detected, while performing a MitMo fraud scheme (Man in the Mobile). Since then, SpyEye and ultimately Ice IX were also included in that list.  The mobile modules used by all of them to capture credentials of the second mobile-based authentication factor developed from the same basis and had only slight improvements, with subtle exceptions.

In this particular case Buguroo’s Anti-Fraud team obtained for Android a sample from an injection appeared in some user’s online bank after he logged in, convincing him to install a security application, using a message like following:

#### reports: to install a free encryption program on your phone, use the following address

In the dynamic analysis we can see how it is self-installed by pretending to be a security solution, and it never tries to hide:

It only shows an activation code to be presumably associated with the user’s entity account. This is the phone ID code (IMEI for GSM and MEID or ESN for CDMA), as discussed below.

The APK package structure is as follows:

The self-signed certificate contains following signature:

In the XML file (AndroidManifest.xml) defining the authorizations required to run the application, attention is drawn to some of them as follows:

As you will notice, authorization is required to receive and send SMS, as well as to check and to modify the phone state, among others.

The structure of the Java application is as follows:

In the class “MainActivity” you can see the code used to display the message with the assumed activation ID:

The main functionality is contained in class “SmsReceiver”, which is in charge of intercepting and forwarding incoming SMS to a server controlled by the attacker. Here are some of the variables used to store captured information, as well as the server to which this information is sent:

One of the main changes compared to previous versions is that the URL is encoded, though in a very simple manner, so that you may obtain it by eliminating the characters “q”, “-” and “=” from the chain.

Notice that, since its first appearance, the complexity of these samples has barely increased, which means that they are still effective and continue meeting the fraudsters’ goals. In the end, if something works, why change it?

Malware Stepper

Existen muchas estrategias de análisis de malware, en este post voy a reflejar una técnica de análisis dinámico que facilita bastante las cosas, voy a llamarla stepping aunque en realidad se basa más en traces que en steps.

El stepping consiste en ejecutar todo el código del malware paso a paso, hasta identificar las llamadas “peligrosas” a la API de Windows, en principio no puede realizar ninguna actividad malévola sin llamar ninguna api, otra cosa es que llame api´s no documentadas, o utilice técnicas de subir a ring0 mediante desbordamientos de buffer, interrupciones o como sea.

El stepping tiene dos problemas:

1. La velocidad, steppear un binario es muy muy lento, para que os hagáis una idea, hacer un stepping de un malware de pocos Kbytes puede tardar varios días.

2. El segundo problema es que realice hooks, infecciones, salto a ring0 .. de manera que los datos interesantes se descifrarán desde otro proceso.

El segundo punto es una limitación de esta técnica, aunque se puede parar el stepping ante un intento de infección, hookeo etc … y continuar manualmente con análisis estático u otros steppings de otros procesos. Esto es solo una técnica y no una herramienta valida para analizar todos los malwares.

En cuanto al lenguaje a utilizar, me interesa combinar el stepping automático con análisis manual, de manera que debería desarrollarse en un lenguage de scripting para ollydebug, immunity, radare etc.

Lo más rápido que he encontrado es ollyscript, más que el ollypython y immunity python, lógicamente porque es más ligero, de hecho, curiosamente el tracing desde ollyscript, va más rápido que manualmente desde ollydebug, cuando el motor es el mismo incluso el ollyscript tiene alguna capa más.

Para acelerar el stepping realicé una comparación de eip con la dirección a partir de la cual se enlazan las librerías, fuera de librerías procedía con step into y en librerías con step over.
En el caso de encontrar un bucle, realicé una rutina llamada saltaBucles que lo detecta, breakpointea las salidas y ejecuta para pasar el bucle de la forma más rápida.

Salir de los bucles y hacer step over en las librerías aceleraba bastante el stepping, no obstante lo que voy a publicar aquí es una versión basada en trace, trace into en el módulo del malware y trace over en los demás módulos, que también es relativamente rápido, ollyscript realiza los trace y los animate de forma bastante eficiente, sobretodo los trace.

El siguiente punto a tener en cuenta, es hasta que punto dejar fluir la ejecución, que apis consideramos peligrosas.
En mi caso tenía un objetivo concreto que es obtener las urls, que algunos casos van cifradas y en otros no.

Tal como he comentado, existen otras técnicas de intercepción de api como el ring3 hooking, el ring0 SSDT patching etc …
Las api que decidí interceptar mediante stepping son las siguientes, describo muy brevemente la razón:

Para detectar api-loaders, infecciones, cambios de permisos en páginas para desempacar o descifrar código:


Crear claves de registro:


Conexiones y aperturas de puertos, posible control remoto, o envio de credenciales:


Acceso a webs ftps, posibles envíos de credenciales:


Ejecución de comandos o para malwares multi multistaged:


Posible convert-channel mediante las netapi:


Se podrían incluir más api interesantes como por ejemplo la cryptoapi, pero tampoco quería cargar mucho el bucle.

En cuanto al motor de traceo condicional, se basa en lo siguiente:

ticnd "eip >= 10000000"
cmp eip, 0
je theend

// Ha entrado en una api, si es una api sospechosa, se loguea y finaliza la ejecución, si no se loguea y continua el traceo

tocnd "eip < 10000000"
jmp engine

En la ventana de log de ollydebug, se puede ver las api que van siendo llamadas, softwares tipo strace/ltrace para windows hay varios, sin embargo este script puedes pararlo cuando quieras de forma manual o programada.

El stepper detecta una llamada interesante y para su ejecución para que el analista pueda continuar de forma manual.

En este caso el fichero se abre a si mismo, posiblemente en alguna parte del fichero no mapeada por el linker, se encuentran datos cifrados. Abrirse a si mismo es una operación típica en virus tipo overlay, por ejemplo un infector de ficheros elf que hice en el 2006: infR3.s

Podéis descargar el OllyScript aquí: Stepper – OllyScript for Malware Análisis


* No es la forma más rápida ni automática de analizar, es un script de ayuda al análisis manual del malware para situaciones puntuales, que ha de ser combinado con análisis manual.
* Un buen complemento es scripts de búsqueda de patrones estáticos, que espero publicar en otro post.
* Esto ejecuta el malware!!, buguroo no se hace responsable del uso inapropiado de este script, recomendamos utilizar máquina independiente o virtual.