APT Article Published

[Español] Este mes la revista Red Seguridad incluye mi artículo sobre APT (Amenazas Persistentes Avanzadas) basado en mi experiencia personal en el trabajo donde hemos encontrado varias veces este tipo de amenazas.

[English] This month the magazine Red Seguridad includes my article about APT (Advanced persistent threats) based on my personal experience at work where we frequently discover this type of threat.

Sin duda los APT son un tema caliente y en el artículo detallo en qué consisten, casos reales de ataques, por qué se producen y son tan exitosos, así como algunas recomendaciones de cómo las empresas deberían protegerse.

No doubt APT are a hot topic and the article details what they are, cases studies of real attacks, why they occur and why they are so successful as well as some recommendations on how companies should protect themselves.

Por desgracia el artículo solo está en español pero si algún lector extranjero está interesado se lo puedo enviar para que lo traduzca con Bing :)

Unfortunately the article is only in Spanish but if a foreign reader is interested I can send a copy so he can translate it with Bing :)

No os perdáis otros artículos que escribo de forma frecuente en revistas de seguridad y mis servicios, que quizás sean de tu interés ;)

Como siempre un placer y ahora a seguir analizando la inseguridad…

Do not miss other articles that I usually write in security magazines and my services, which may be of interest to you ;)

My pleasure, as usual, and now on to keeping analyzing insecurity…

— Simon Roses Femerling

Posted in Hacking, Pentest, Security | Tagged , , , , , | Leave a comment

AppSec: Static Analysis Using Visual Studio 2010 for Hunting C/C++ Bugs

[Español] Para este artículo hablaremos de una magnífica herramienta como es Visual Studio 2010, el entorno de desarrollo de Microsoft, que utilizo a diario para realizar auditorías de código en C/C++ o .NET. Cuando imparto clases sobre SDL es frecuente encontrar programadores que no conocen las herramientas de seguridad que ofrece Visual Studio, incluso me sucede con expertos en seguridad que tampoco las conocen y esto debe cambiar.

[English] For this article we’ll talk about a magnificent tool such as Visual Studio 2010, Microsoft development environment, which I use on a daily basis to conduct code audits of C/C++ or.NET. When I teach the SDL courses it is common to find developers who do not know the security tools offered by Visual Studio, this even happens with security experts who do not know them either, and this must change.

Como ya he mencionado Visual Studio trae interesantes herramientas para escribir código seguro como programador o para buscar vulnerabilidades como auditor. Para ello estudiaremos dos herramientas que son identificación de funciones inseguras y análisis estático de código inseguro.

As I have already mentioned Visual Studio brings interesting tools to write secure code as a programmer or to look for vulnerabilities as auditor. To do this we will look at two tools that are unsafe functions identification and static analysis of insecure code.

Identificación de Funciones Inseguras / Unsafe Functions Identification

A estas alturas debería ser ampliamente conocido que las librerías de C contienen una serie de funciones consideradas inseguras que son la raíz de muchos avisos de seguridad. Microsoft consciente de ello en el 2010 publicó una extensión para Visual Studio para identificar estas funciones inseguras, además de prohibir su uso según el SDL.

At this stage should be widely known that C libraries contain a number of functions that are considered insecure and are the root of many security advisories. Aware of this at 2010 Microsoft released an extension for Visual Studio to identify these unsafe functions, as well as banning its use according to the SDL.

En la Fig. 1 podemos ver un código a modo de ejemplo que contiene dos funciones inseguras como son sprintf y strcpy. Nota: en este ejemplo ambas funciones no pueden ser controladas por un atacante pero lo que nos interesa es identificar estas funciones inseguras.

In Fig. 1 we can see a code example that contains two unsafe functions such as sprintf and strcpy. Note: in this example both functions cannot be controlled by an attacker, but what interests us is to identify these unsafe functions.

Fig. 1 – Ejemplo de funciones inseguras / Insecure function example

En la Fig. 2 Visual Studio, con la extensión de funciones insegura instalada, nos subraya la función sprintf en color violeta indicándonos algún problema. Al poner el cursor encima vemos que nos sale una ventana con el mensaje que esta función es insegura y prohibida según el SDL y nos ofrece alternativas seguras. Igualmente si nos ponemos encima de strcpy nos dará un mensaje parecido.

In Fig. 2 Visual Studio, with the insecure functions extension installed, point us at function sprintf in purple indicating a problem. When putting the cursor above we see that we get a window with the message that this function is unsafe and banned according to the SDL and offers safe alternatives. Also if we are on top of strcpy it will give us a similar message.

Fig. 2 – Función Insegura sprintf / Sprintf insecure function

Digamos que compilamos el código porque no hemos visto las funciones inseguras, entonces Visual Studio nos dará un aviso de error en la compilación de que existen funciones inseguras como se puede apreciar en la Fig. 3.

Let’s say that we compile the code because we have not seen the insecure functions, then Visual Studio will give us a warning notice in the compilation that there are unsafe functions as shown in Fig. 3.

Fig. 3 – Función insegura identificada al compilar el código / Unsafe function identified at compilation time

Sin duda esta extensión es de gran ayuda para identificar rápidamente las funciones inseguras que son más de 100 cuando estamos auditando código.  

No doubt this extension is of great help to quickly identify unsafe functions as there are more than 100 when we are auditing code.

Análisis Estático de Código Inseguro / Static Analysis of Insecure Code

Visual Studio incorpora una potente herramienta de análisis estático para identificar código vulnerable en C/C++ que todo programador debería utilizar para validar su código. Algunas clases de errores que detecta la herramienta son:

  • Desbordamiento de buffer
  • Memoria sin inicializar
  • Referencia a puntero nulo

En la Fig. 4 tenemos un código modificado del ejemplo anterior conteniendo una clásica vulnerabilidad. En este fallo se copia una cadena de carácter A en un buffer, buf, de menor tamaño que provoca un desbordamiento de buffer (buffer overrun).

Visual Studio includes a powerful static analysis tool to identify vulnerabilities in code for C/ C++ that every programmer should use to validate its code. Some bug classes detected by the tool are:

  • Buffer overflow / Buffer overrrun
  • Un-initialized memory
  • Null pointer dereference

In Fig. 4 we have a modified code from previous example containing a classical vulnerability. In this bug a string, A, is being copied to a buffer, buf, of smaller size causing a buffer overflow.

Fig. 4 – Desbordamiento de buffer / Buffer overflow

Utilizamos la potente herramienta de análisis estático para buscar vulnerabilidades que ejecutamos desde la línea de comando con el parámetro /analyze. En la Fig.5 podemos ver cómo se nos informa de dos errores, C6202 y C6386, en referencia al desbordamiento de buffer.

We use the powerful static analysis tool to find vulnerabilities which we run from the command line with the parameter /analyze. In Fig. 5 we can see how it informs us of two warnings, C6202 and C6386, in reference to the buffer overflow.

Fig. 5 – Utilizando VS /analyze para identificar vulnerabilidades / Using VS /analyze to identify vulnerabilities

En la Fig. 6 podemos apreciar otra clase de vulnerabilidades que aparece con frecuencia cuando se libera memoria del mismo puntero en varias ocasiones. En este ejemplo si foo es verdadero se ejecuta un trozo de código y al final se libera el puntero. El problema es que al final de la función también se libera el mismo puntero. Tenemos dos mensajes de aviso C6001 y C6011 en referencia a uso de memoria sin inicializar y referencia a  puntero nulo.

In Fig. 6 we can appreciate another class of vulnerabilities that often appears when memory is being freed on the same pointer on several occasions. In this example if foo is true it runs a piece of code and finally releases, free, the pointer. The problem is that the same pointer is also being released, free, at the end of the function. We have two warnings C6001 and C6011 messages in reference to un-initialized memory and null pointer dereference.

Fig. 6 – Referencia a puntero nulo / Null pointer dereference

El último ejemplo de código vulnerable (Fig. 7) es un fallo donde el programador se ha equivocado en la sentencia For ya que el rango de la variable buff comienza en 0 y termina en 14 y en el For se ha utilizado el mismo índice, 15 en este caso. Por tanto en este ejemplo se produce un desbordamiento de buffer ya que el índice esta fuera de rango.  

The last example of vulnerable code, Fig. 7, is a bug where the programmer has mistaken the For loop as the variable buff range starts at 0 and ends at 14 and the For loop uses the same index declared in buff, 15 in this case. In this example there is a buffer overflow due to the declared index being out of range.

Fig. 7 – Índice fuera de rango / Index out of range

Sin duda Visual Studio es una poderosa herramienta para auditar código que debería formar parte de nuestro arsenal. Los ejemplos presentados no distan demasiado de ejemplos reales que he visto auditando código, por desgracia muchas veces la realidad supera a la ficción.

La herramienta de análisis estático es más efectiva si la combinamos con el Standard Annotation Language (SAL), que nos permite definir los parámetros de las funciones por lo que aportamos conocimiento a la herramienta y puede profundizar en sus análisis para identificar fallos, pero este uso avanzado lo dejaremos para otro artículo :)

¿Y tú que herramientas utilizas para análisis estático?

Undoubtedly Visual Studio is a powerful tool to audit code that should be part of our arsenal. The presented examples are not too far from real examples I’ve seen auditing code, unfortunately often fact is stranger than fiction.

The static analysis tool is most effective if we combine it with the Standard Annotation Language (SAL) that allows us to define the functions prototypes for which you provide knowledge to the tool so it can go deeper with the analysis to uncover bugs, but I leave this advanced usage for another article :)

What tools do you use for static analysis?

— Simon Roses Femerling

Posted in Microsoft, Pentest, SDL, Security, Threat Modeling | Tagged , , , , , , , , | 1 Comment

Wireless Pentester Guide on Automated Wireless Cracking

Hoy en día existen diversas soluciones para ayudarnos a realizar auditorías wireless,  lejos han quedado los días de utilizar aircrack en la línea de comandos. Ahora contamos con potentes herramientas que automatizan todo el proceso de romper redes wireless de forma sencilla y rápida. Para este artículo sólo estamos interesados en seis herramientas gratis, aunque soluciones comerciales como SILICA o The Portable Penetrator también pueden ser de interés para el lector.

Today there are various solutions to help us carry out wireless assessments, far were the days of using aircrack in the command line. We now have powerful tools that automate the entire process of breaking wireless networks quickly and easily. For this article we are only interested in six free tools but commercial tool such as SILICA or The Portable Penetrator solutions can also be of interest to the reader.

Wepbuster

Wepbuster es una popular herramienta que ha quedado algo obsoleta aunque funciona perfectamente. Wepbuster identificará todos los Access Points (AP) cercanos y comenzará a ejecutar los distintos ataques incluidos en la suite de aircrack.

Es muy fácil de utilizar y no requiere interacción por parte del usuario. Las Fig. 1 y 2 muestran Wepbuster en acción.

Wepbuster is a popular tool which is a bit obsolete although it works perfectly. Wepbuster  will identify every Access Point (AP) nearby and launch all attacks included in the aircrack suite.

It is very easy to use and requires no user interaction. The Fig. 1 and 2 show Wepbuster in action.

Fig. 1 – Wepbuster

Fig. 2 – Wepbuster cracking

Grim Wepa

Esta herramienta escrita en java nos permite realizar distintos ataques en redes wireless. El usuario debe seleccionar el AP y el ataque a ejecutar.  En la Fig. 3 vemos el GUI de grim wepa.

This tool written in java allows us to perform various attacks in wireless networks. The user must select the AP and the attack to run. In the Fig. 3 we see the grim wepa GUI.

Fig. 3 – Grim WEPA GUI

Wiffy

Wiffy es una sofisticada herramienta automatizada para auditar redes wireless que nos ofrece interesantes opciones como realizar distintos ataques, denegación de servicios (DoS), crear rainbow tables o capturar información de una red mediante karmasploitation (karma + metasploit).

La Fig. 4 es la pantalla de inicio de wiffy y en la Fig. 5 wiffy ha identificado todos los AP cercanos y nos pide cuál atacar. Una vez seleccionado el objetivo AP, wiffy ejecutará todos los ataques de la suite aircrack de forma automática.

Wiffy is a sophisticated automated tool to audit wireless networks that offers interesting features such as performing various attacks, denial of service (DoS), create rainbow tables, or capture information on a network by using karmasploitation (karma + metasploit).

Fig. 4 is wiffy main window and in Fig. 5 wiffy has identified all nearby APs and asks us which attack to execute. After selecting the target AP, wiffy launches all attacks in the aircrack suite automatically.

Fig. 4 – Wiffy menu

Fig. 5 – Wiffy cracking

Wifite

Wifite es una versátil herramienta que a través de un simple GUI nos permite configurar la sesión de ataque (ver Fig. 6) y una vez configurados los parámetros se abre una ventana en modo texto. Es en esta ventana donde se realizan los ataques a todos los AP identificados (ver Fig. 7)

En cualquier momento podemos interactuar con la sesión pulsando Ctrl+C para cambiar el ataque o pasar a otro objetivo.

Wifite is a versatile tool that through a simple GUI allows us to configure the attack session, see Fig. 6, and once configured the settings a window in text mode is opened. It is in this window where attacks are executed against all identified AP. See Fig. 7.

At any time we can interact with the session by pressing CTRL+C to change the attack or move on to another target.

Fig. 6 – Wifite GUI

Fig. 7 – Wifite cracking

Fern WIFI Cracker

Fern WIFI Cracker es una potente herramienta escrita en python que nos permite realizar distintos ataques mediante un elegante GUI. En la Fig. 8 podemos ver la pantalla de inicio de la herramienta donde se ha realizado un escaneo y se han detectado varios AP.

Ahora ya podemos seleccionar un objetivo y el ataque que nos interese y Fern hará el resto de forma automatizada (ver Fig. 9).

Algunas ventajas de Fern son su extremada sencillez de uso, capacidad de ejecutar distintos ataques y que las contraseñas obtenidas son almacenadas en una base de datos.  Desafortunadamente a veces el programa se cuelga.

Fern WIFI Cracker is a powerful tool written in python which allows you to perform various attacks through a sleek GUI. In Fig. 8 we can see the main window where a scan has been done and has detected several APs.

Now we can select the target AP and the attack that interests us and Fern will do the rest automatically (see Fig. 9).

Some advantages of Fern are its extreme ease of use, capable of executing various attacks and obtained passwords are stored in a database. Unfortunately sometimes the program hangs.

Fig. 8 – Fern GUI

Fig. 9 – Fern cracking

Gerix

Gerix es la única herramienta de las analizadas incluida por defecto en Backtrack (4 y 5) y es posiblemente la más sofisticada y potente, ya que nos permite realizar distintos ataques o actuar como un AP malicioso de forma sencilla.

En la Fig. 10 vemos el panel de configuración de Gerix, donde podemos seleccionar el objetivo AP. El siguiente paso es ir probando los diferentes ataques, ver Fig. 11.

Gerix is the only tool of the analyzed included by default in Backtrack (4 and 5) and it is possibly the most sophisticated and powerful tool, allowing us to perform various attacks or act as a malicious AP in a simple way.

In the Fig. 10 we see Gerix configuration panel and where we can select the target AP. The next step is to try different attacks, see Fig. 11.

Fig. 10 – Gerix GUI

Fig. 11 – Gerix cracking

Conclusiones

A pesar de que existen más herramientas que nos permiten automatizar ataques wireless las aquí descritas posiblemente sean las mejores y nada tienen que envidiar a las soluciones comerciales. Lógicamente estas herramientas tienen mucho más potencial de lo descrito aquí, por eso recomiendo al lector que juegue con ellas. Además ninguna herramienta es la panacea por lo que el lector debería usar todas o varias por lo menos.

Al ser gratis y de código abierto estas herramientas son una sólida base para poder personalizar a nuestras necesidades y no es demasiado difícil añadirles nuevas funcionalidades, como por ejemplo una vez comprometida un AP realizar ataques a los sistemas utilizando metasploit de forma automatizada. ¿Algún lector quiere esponsorizar este proyecto? :)

¿Y tú que herramientas utilizas para auditar wireless?

Despite the fact that there are more tools that allow us to automate wireless attacks the described here may be the best and have nothing to envy to commercial solutions. Of course these tools have much more potential than what was described here, that is why I recommend the reader to play with them. Also no tool is a panacea and therefore the reader should use several or all of them at the very least.

These free and open source tools are a good starting point to customize for our needs and it is not too difficult to add new features like for example once an AP is compromised to execute  attacks on systems using metasploit in an automated manner. Maybe a reader wants to sponsor this project? :)

What tools do you use for wireless assessments?

— Simon Roses Femerling

Posted in Hacking, Pentest, Security, Technology, Wireless | Tagged , , , , , , , | Leave a comment