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

This entry was posted in Microsoft, Pentest, SDL, Security, Threat Modeling and tagged , , , , , , , , . Bookmark the permalink.

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

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.