Reconstructing JavaScript Exploit

[Español] Recientemente cayó en mis manos un PDF malicioso y como no podía ser de otra manera decidí analizarlo.  Se sabe que en los últimos años los atacantes han estado usando ficheros PDF y SWF para explotar vulnerabilidades e infectar a sus víctimas. Este vector de ataque es uno de los preferidos de las Amenazas Persistentes Avanzadas (APT).

[English] Recently a malicious PDF fell into my hands and naturally I decided to analyze it. It is known that in recent years attackers have been using PDF and SWF files to exploit vulnerabilities and infect their victims. This attack vector is one of the preferred methods of the Advanced Persistent Threats (APT).

Lo primero que nos interesa es determinar el contenido del PDF y para ello utilizamos las PDFtools que nos permiten analizar PDF. Ejecutamos la herramienta pdfid para ver el contenido del fichero y vemos que contiene código JavaScript (ver Fig. 1), que generalmente es utilizado para explotar vulnerabilidades. Si encontramos JavaScript y OpenAction en el mismo  PDF nos interesa analizarlo 🙂

First thing of interest to us is to determine the content of the PDF and for this we use the PDFtools that allow us to analyze PDFs. We run the pdfid tool to view the content of the file and we see that it contains JavaScript (see Fig. 1), which is generally used to exploit vulnerabilities. If we find JavaScript and OpenAction in the same PDF we must analyze it 🙂

Nota PDFtools: para utilizar estas herramientas con Python 2.7 o superior debemos editar los ficheros Python y actualizar la versión!

PDFtools Note: to use these tools with Python 2.7 or higher we must edit the Python files and update the version!


Fig. 1 – PDFtools en acción / PDFtools in action

Ahora que ya sabemos que el PDF contiene código JavaScript podemos usar la herramienta PDFStreamDumper. Esta herramienta es magnífica para realizar análisis de malware.

Now that we know that the PDF contains JavaScript code we can use the PDFStreamDumper tool. This tool is great for malware analysis.

Abrimos el PDF con PDFStreamDumper y en el objeto 0x74FB-0x7B48 encontramos código JavaScript sospechoso (Fig. 2).  Ahora debemos copiar este código desde la propia ventana de texto o pinchando encima del objeto y con botón derecho seleccionar guardar.

Open the PDF with PDFStreamDumper and at object 0x74FB-0x7B48 we find suspicious JavaScript code (Fig. 2). Now we copy this code from text window or by clicking on the object and right mouse button, select save.


Fig. 2 – PDF malicioso en PDFStreamDumper / Malicious PDF under PDFStreamDumper

El código que obtenemos se puede apreciar en la Fig. 3.

The code we get can be seen in Fig. 3.


Fig. 3 – Javascript Exploit / JavaScript Exploit

Observando el código podemos determinar que es un exploit JavaScript muy enrevesado para evitar ser detectado.  Ahora lo que nos interesa es determinar qué hace este exploit por lo debemos hacer ingeniería inversa.

Utilizando la herramienta Malzilla, otra sofisticada herramienta de análisis, insertamos el código JavaScript con algunos pequeños cambios para poder ser analizado en el intérprete JavaScript que la herramienta incorpora.

Observing the code we can determine that it is a JavaScript exploit which is heavily obfuscated to avoid being detected. What we want to do now is to determine what the exploit does by reverse it.

Using Malzilla, another sophisticated analysis tool, we insert the JavaScript code with some minor changes so it can be analyzed in the JavaScript interpreter the tool incorporates.


Fig. 4 – Ejecutando el exploit en Malzilla / Executing the exploit in Malzilla

En la Fig. 4 podemos ver el resultado de ejecutar el código JavaScript malicioso modificado. Una de las técnicas que el exploit utiliza para no ser detectado es el uso de la función Eval() para concatenar dos cadenas de texto que se convierten en código y que se ejecutan mediante el intérprete JavaScript. El resultado son tres sentencias JavaScript.

Nuestro siguiente paso es analizar el código para intentar reconstruir el exploit malicioso. En la Fig. 5 podemos ver las distintas técnicas que el exploit utiliza con el fin de evitar que los anti-virus le detecten.

In Fig. 4 we can see the result of running the modified malicious JavaScript code. One of the techniques of obfuscation is the use of the Eval() function to concatenate two strings that are converted into code that is executed by the JavaScript interpreter. The result is three JavaScript sentences.

Our next step is to analyze the code to try to rebuild the malicious exploit. In Fig. 5 we can see the different obfuscate techniques that the exploit uses to avoid being detected by the anti-virus.


Fig. 5 – Exploit ofuscado / Obfuscated exploit

Los métodos que el exploit utiliza para ocultarse son:

  1. La función adobeexp recibe 2 parámetros: unescape y “%”.
  2. Las variables ddd y VZxgbuj apuntan a unescape.
  3. En la siguiente línea encontramos una shellcode oculta. El exploit llama a la función urpl, que tiene 2 parámetros: “%” y la shellcode. Esta función sustituye la etiqueta NAXX por “%u” y devuelve la shellcode en formato Unicode.
  4. En esta línea se ejecuta un unescape, VZxgbuj, pero antes se concatenan varias cadenas de texto formado: %u0c0c%0c0c. La variable Zod almacena lo que se conoce como el NOP slide.
  5. Utilizando la técnica de Eval() se concatenan dos cadenas de texto para formar una sentencia ejecutable, preparando la dirección de retorno para que al explotar la vulnerabilidad se ejecute el código malicioso, NOP slide + shellcode.
  6. y 7. El exploit utiliza los demás Eval() para preparar el buffer malicioso que llenará el heap, lo que se conoce como Heap Spraying, que consiste en llenar todo el espacio posible en el heap del proceso con código malicioso y al explotar la vulnerabilidad se  redirigirá la ejecución del proceso a una dirección del heap donde reside el código malicioso.

Hemos destripado el exploit y tenemos una clara idea de su funcionamiento. En la Fig. 6 podemos leer el verdadero código del exploit.

The methods that the exploit uses for obfuscation are:

  1. The adobeexp function takes 2 parameters: unescape and “%”.
  2. The variables ddd and VZxgbuj point to unescape.
  3. On the next line we find an obfuscated shellcode. The exploit calls the function urpl, which has 2 parameters: “%” and the shellcode. This function replaces the NAXX tag by “%u” and returns the shellcode in Unicode format.
  4. In this line the code runs an unescape, VZxgbuj, but before it concatenates several strings to form: %u0c0c%0c0c. Now Zod variable stores what is known as the NOP slide.
  5. Using the Eval() technique it concatenates two text strings to form a executable sentence, which prepares the return address containing the malicious code when exploiting the vulnerability, NOP slide + shellcode.
  6. And 7. The exploit uses Eval() again to prepare the malicious buffer that will fill the heap, what is known as Heap Spraying, which consists in filling all possible heap space in the process with malicious code and when exploiting the vulnerability it changes the execution flow of the process to call an address on the heap where resides the malicious code.

We have reversed the exploit and have a clear idea of its operation. In Fig. 6 we can read the exploit code without obfuscation.


Fig. 6 – Exploit / Exploit

El objetivo de este post era analizar y destripar este exploit. Nuestro siguiente paso sería analizar la shellcode. En la Fig. 7 se puede ver cómo he vuelto a modificar el exploit para obtener una shellcode en formato Unicode que sea fácil de analizar. El procedimiento que he seguido para ello es convertir la shellcode en ejecutable y analizarlo con IDA Pro pero eso es otra historia 🙂

The objective of this post was to analyze and reverse this obfuscated exploit. Our next step would be to analyze the shellcode. In Fig. 7 you can see how I modified again the exploit code to get a shellcode in Unicode format which is easy to analyze. The procedure I followed was to convert the shellcode to executable code and analyze it with IDA Pro but that’s another story 🙂


Fig. 7 – Extrayendo la shellcode / Extracting the shellcode

A lo largo de este post hemos utilizado potentes herramientas de análisis y estudiado el procedimiento para analizar código malicioso, una habilidad necesaria hoy en día con tanto PDF y  SWF malicioso que circulan por Internet.

Si el lector tiene algún código malicioso que quiera analizar para el blog que me lo envíe por favor 🙂

¿Que exploits maliciosos te has encontrado?

In this post we have used powerful analysis tools and studied the procedure to analyze malicious code, a necessary skill today with so many malicious PDF and SWFs that circulate on Internet.

If the reader has some malicious code you want us to analyze for this blog sent it our way please 🙂

Have you found any malicious exploits?

— Simon Roses Femerling

This entry was posted in Hacking, Pentest, Security and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.