AppSec: Security Code Review Process

[Español] En mi trabajo paso la mayor parte del tiempo auditando código y he pensado que sería interesante para el lector contar un poco nuestro proceso y de paso ver cómo lo hacen los demás.

[English] I spend most of the time at work auditing code and I thought it would be interesting for the reader to explain our process and see how others do it.

Como no podía ser de otra manera seguimos el SDL de Microsoft :) y todos los desarrollos internos tienen que pasar una serie de controles de seguridad. Para este artículo nos enfocaremos en la auditoría de código únicamente.

Nuestro proceso es muy fácil de seguir para los grupos de desarrollo, ya que tenemos que tener en cuenta que la gente de seguridad está para ayudar y no complicar las cosas.

En la Fig. 1 podemos ver una versión aproximada del proceso que seguimos,  que creo que es muy fácil de entender por lo que no entraré a detallar.

As it could not be otherwise we follow Microsoft SDL :) and all internal developments must pass a series of security checks (security gates). For this article we will focus on code review only.

Our process is very easy to follow for development groups, we must bear in mind that the security teams are here to help and not to complicate things.

In Fig. 1 we can see an approximate version of the process we follow which I think is very easy to understand so I will not explain the detail.

Fig. 1 – Proceso Auditoría de Código / Code Review Process

Una parte importante del SDL son las constantes mejoras a los procesos, herramientas y formación como se puede ver en el punto 14. Esto es fundamental para mantener un buen nivel  de seguridad con las últimas tecnologías.

Siguiendo este proceso hace tiempo que desarrollé una pequeña herramienta (lo siento pero no disponible por el momento) para ser más efectivo en auditorías de código llamada WildFire, que incorpora la mayoría de las etapas del proceso anterior.

An important part of the SDL is the continuous improvements to processes, tools and training as you can see in point 14. This is essential to maintain a good level of security with the latest technologies.

Following this process some time ago I developed a small tool (sorry but not available at the moment) to be more effective in code reviews called WildFire which incorporates most of the stages of the previous process.

Lo interesante de WildFire son algunas características como:

  • Analiza todo el código para obtener líneas de código y comentarios para ayudarnos en la estimación de tiempo, identifica vulnerabilidades (análisis estático básico), clasifica los ficheros en función de tipo, etc.
  • Genera un informe con los hashes de todo el código para enviar al cliente
  • Simple UI
  • Generación de informes
  • Utiliza un modelo de caja negra en el sentido que no intenta entender o compilar el código y puede analizar distintos lenguajes de programación

The interesting thing about WildFire are some features like:

  • Analyses code to get lines of code and comments to help us in the estimation of time, identifies vulnerabilities (basic static analysis), classifies files based on type, etc.
  • Generates a report with the hashes of all the code to send to the client
  • Simple UI
  • Report generation
  • Uses a black box approach in the sense that it does not try to understand or compile the code and can analyze various programming languages

WildFire es una herramienta bastante efectiva para mis necesidades aunque no es la única que utilizo, como por ejemplo Visual Studio, que es otra potente herramienta para realizar auditorías de código.

Desde la Fig. 2 hasta la Fig. 5 podemos ver WildFire en acción.

WildFire is a pretty effective tool for my needs although it is not the only one that I use as for instance Visual Studio, which is another powerful tool to perform code reviews

From Fig.  2 to Fig. 5 we can see WildFire in action.

Fig. 2 – Pantalla de Inicio / Home Screen

Fig. 3 – Análisis Completado / Analysis Completed  
Fig. 4 – Sumario del análisis / Analysis Summary
Fig. 5 – Visualización de código / Code Visualization

Una parte importante es la estimación de tiempo que nosotros realizamos mediante dos pasos, primero un formulario que recoge información del proyecto a revisar y segundo tras obtener el código utilizamos una tool diseñada para este fin, ya sea WildFire u otras que también disponemos. En OWASP podemos encontrar información sobre métricas en código.

Sin duda contar con un proceso bien detallado y las herramientas adecuadas es fundamental para una auditoria de código aunque no es suficiente, también debemos contar con las personas adecuadas (talento y formación).

Y vosotros como realizáis auditorias de código?

An important part is the estimation of time which we carry out by a two-step process, first a form that collects information from the project to review and second after obtaining the code use a tool designed for this purpose either WildFire or other tools that we also have available. In OWASP we can find information about code metrics.

Without a doubt having a good detailed process and the right tools is essential for a code review although it is not enough, we must also have the right people (talent and training).

How do you perform code reviews?

— Simon Roses Femerling

Posted in Microsoft, OWASP, Pentest, SDL, Security, Technology | Tagged , , , , | Leave a comment

Reversing Android Crackmes for Fun

[Español] Hace tiempo que quería escribir sobre crackme en Android, ya que son un magnífico ejercicio para aprender técnicas de ingeniería inversa para Apps que luego podemos aplicar para analizar malware o buscar vulnerabilidades ;)

Para este post he pensado que sería interesante comentar algunas herramientas que podemos usar y por desgracia los pocos crackmes que existen para Android. No es mi intención escribir un tutorial de ingeniería inversa, eso lo dejo para el lector!

[English] I have been waiting to write about Android crackmes for a while since they are a wonderful exercise to learn reverse engineering techniques for Apps that we can later apply to analyze malware or to find vulnerabilities ;)

For this post I thought it would be interesting to comment on some tools you can use and unfortunately the few crackmes that exist for Android. It is not my intention to write a tutorial on reverse engineering, that I leave to the re ader!

Herramientas / Tools

Como Android es la plataforma de moda para los hackers se han desarrollado diversas herramientas que podemos utilizar y que voy a comentar a continuación.

  • Android SDK: el kit oficial de Google para desarrollar Apps, donde podemos encontrar utilidades como el Emulador para crear imágenes Android con las que jugar, el ADB, una potente utilidad que nos permite comunicarnos con Android y realizar diversas tareas, así como las herramientas de desarrollo.
  • Androguard: estupendo kit para realizar ingeniería inversa, está escrito en python por lo que es ideal para escribir scripts
  • Dex2jar: convierte los binarios de Android (.dex) en ficheros java (.class) para facilitar su análisis
  • JAD: decompilador java
  • Smali: ensamblador / desensamblador del formato Dex
  • Jd-gui: decompilador java

Existen más herramientas pero éstas son un buen comienzo. Aparte en mi caso también utilizo varias herramientas que he desarrollado para esta tarea y que algún día publicaré :)

As Android has become hacker’s playground various tools have been developed that we can use and we will comment below.

  • Android SDK: the official kit from Google to develop Apps, where you can find utilities as the emulator to create Android images to play with, the ADB, a powerful utility that allows us to communicate with Android and perform various tasks, as well as the development tools.
  • Androguard: super kit for reverse engineering, is written in python so it’s ideal for writing scripts
  • Dex2jar: convert Android binaries (.dex) to Java (.class) files to facilitate analysis
  • JAD: java decompiler
  • Smali: assembler / disassembler of the Dex format
  • Jd-gui: java decompiler

There are more tools but the discussed here are a good start point. In my case I also use several tools that I have developed myself for this task, which someday I will publish :)

Crackmes

Como mencioné anteriormente existen muy pocos crackmes de Android, en la actualidad yo sólo conozco 4. Comentaré 2 de los crackmes aunque no daré ninguna solución al reto, y los otros 2 para que el lector se entretenga.

As mentioned previously there are very few Android crackme, I only know 4. I will comment on two crackmes although I will not give any solution to the challenge, and the other two crackmes for the reader’s entertainment.

Crackme1hpys / Crackme1hpys

Los chicos de Hack Players publicaron un reto crackme en diciembre 2010 que consistía en averiguar la contraseña de la aplicación. Aunque superé el reto llegué tarde ;)

En la Fig. 1 podemos ver que al ejecutar el crackme se nos pide un usuario y contraseña que a priori no conocemos. Utilizando las herramientas antes descritas comenzamos el análisis del crackme.

The guys from Hack Players published a crackme challenge in December 2010 which consisted in finding out the username and password for the application. Although I did overcome the challenge I did arrive late ;)

In the Fig. 1 we can see that when you run the crackme it is asking for a username and password that we don’t know. Using the tools described above we start analyzing the crackme.

Fig .1 – Pantalla de inicio / Main screen

En la Fig.2 introducimos un usuario y contraseña al azar para ver qué mensajes nos proporciona el crackme. Muchas veces con los mensajes de error podemos obtener información interesante. 

In the Fig.2 we enter a username and password at random to see what messages crackme provides us with. Many times error messages provide interesting information.

Fig. 2 – Contraseña inválida / Invalid password

En este punto hemos analizado el crackme y hemos obtenido el usuario y contraseña correctos como se puede ver en la Fig. 3. Lo cierto es que es un reto fácil aunque entretenido.

Estrategias de análisis: para estos crackmes o incluso cualquier App tenemos dos estrategias principales: análisis estático del código o análisis dinámico manipulando el App.  

At this point we have analyzed the crackme and obtained the correct username and password as you can see in the figure 3. It is true this is an easy challenge but entertaining as well.

Analysis strategies: for these crackmes or even any App we have two main strategies: static code analysis or dynamic analysis by manipulating the App.

Fig. 3 – Hemos superado el reto! / Challenge  overcome!

Aquí podréis encontrar la solución.

Here you will find the solution.

Serie crackme0X! / Crackme0X! series

Deurus, el alias del autor, publicó 3 crackmes (crackme01, crackme02 y crackme03) aunque por desgracia la página que los alberga y que era un magnífico portal de crackmes ya no está disponible y desde aquí esperamos que vuelva algún día.

Para estos crackmes seguimos el procedimiento del anterior crackme y en la Fig. 4 podemos ver cómo hemos obtenido un valor válido.

Los crackme02 y crackme03 los dejo para que el lector se entretenga :)

Deurus, author alias, published 3 crackmes (crackme01, crackme02 and crackme03) but unfortunately the page containing them that was a magnificent portal of crackmes is no longer available and from here we hope it returns someday.

For these crackmes we follow the procedure earlier described with the above crackme and in the Fig. 4 we can see how we have obtained a valid value.

We leave crackme02 and crackme03 to the reader for his amusement :)

Fig. 4 – Jugando con Crackme01 / Playing with crackme01

Los crackmes han sido siempre un buen ejercicio para aprender ingeniería inversa, análisis de aplicaciones, buscar vulnerabilidades y para algunos quitar protecciones. Hoy en día existen crackmes de todas clases y lenguajes.

Yo sólo conozco estos 4 crackmes para Android por lo que si el lector conoce alguno más le agradeceré que me envíe un email, por favor :)

Qué crackmes recomiendas?

Crackmes have always been a good exercise to learn reverse engineering, applications analysis, how to look for vulnerabilities, and for some remove protections. Today there are crackmes of all classes and languages.

I only know these 4 crackmes for Android so if the reader knows some more send me an email, please :)

What crackmes do you recommend?

— Simon Roses Femerling

Posted in Hacking, Pentest, Security, Technology | Tagged , , , , , , , | 1 Comment

Wake Up Call to MBA Schools: Security & Privacy Concepts

[Español] Ya hace más de un año que finalicé mi Executive MBA en una conocida escuela de negocios, que fue una experiencia interesante y enriquecedora, y por otro lado llevo en el mundo de la seguridad informática muchos años en los que he visto casi de todo. Por eso he pensado que para este post sería interesante comentar una carencia que tienen la mayoría de programas MBA en relación con mi carrera profesional.

[English] It has been more than a year since I did finish my Executive MBA at a well-known business school, being an interesting and rewarding experience, and on the other hand I have been working in the world of computer security for many years where I’ve seen almost everything. That is why I thought that for this post it would be interesting to discuss an existing gap in most MBA programs related to my professional career.

En las diferentes asignaturas ves de forma rápida multitud de conceptos sobre operaciones, finanzas, marketing, estrategia, RSC, emprendedores, etc. y si es una escuela moderna seguramente también un curso de tecnología. Es en esta asignatura donde echo en falta algo más de contenido  sobre seguridad y privacidad para los tiempos que corren.

In the different subjects you quickly view multitude of concepts from operations, finance, marketing, strategy, CSR, entrepreneurship, etc. and if it is a modern school maybe a technology course. It is in this subject where I miss something about security and privacy concepts for the times we are in.

Las escuelas de negocios proclaman que crean a los líderes del mañana pero en la mayoría de casos estos líderes no salen preparados para abordar un tema como es la seguridad y privacidad. Unos conocimientos básicos son igualmente necesarios que en otras áreas como finanzas, estrategia o marketing para que la compañía goce de una buena salud.

Business schools claim that they create the leaders of tomorrow, but in most cases these leaders do not come prepared to address a topic such as security and privacy. A few basic skills are equally required as other areas such as finance, strategy and marketing for the company to enjoy a good health.

Nadie puede negar que prácticamente todas las empresas del mundo utilizan la tecnología de forma diaria mediante correos electrónicos, blog corporativos, navegación por Internet, redes sociales, dispositivos móviles o la mítica Nube, incluso muchas empresas utilizan la tecnología como palanca de innovación.  Sin embargo a pesar de todo este uso la seguridad y privacidad suelen ser temas olvidados por la alta dirección, grave error.

No one can deny that almost all the companies in the world use technology on a daily basis through e-mails, corporate blogs, browsing the Internet, social networks, mobile devices or the mythical Cloud, even many businesses use technology as a lever for innovation. But despite all this security and privacy issues are being neglected by top management, big mistake.

Si algo hemos aprendido en 2011 es que nadie está a salvo de ser atacado: empresas como RSA, HBGary o Sony han caído victimas de grupos como Anonymous u otros atacantes mediante ataques muy sencillos y ampliamente conocidos. Estos ataques podrían haber sido evitados si las compañías contaran con los recursos apropiados, y para ello los que toman las decisiones tienen que tener la información necesaria.

If we have learned anything in 2011 is that nobody is safe from being attacked: companies such as RSA, HBGary or Sony have fallen victims of groups such as Anonymous or other attackers using very simple and widely known attacks. These attacks could have been avoided if companies had the appropriate resources and for that those who take decisions must have all the necessary information.

Es cierto que existen MBA enfocados a tecnología o específicos en seguridad que cubren esta área, pero no es suficiente. En mi opinión todas las escuelas de MBA deberían contener una sección con conceptos sobre seguridad y privacidad, ya que es fundamental que la alta dirección entienda y ejerza buenas prácticas de seguridad.

It is true that there are MBA focused on technology or even security specific covering this area but this is not enough. In my view all MBA schools should contain a section with security and privacy concepts, given that it is essential that senior management understand and exercise good security practices.

La información al igual que los empleados son posiblemente los dos activos más valiosos de cualquier empresa pero demasiadas veces no se saben identificar, valorar o cuantificar, y  ambos activos quedan tocados si la seguridad de la empresa se ve comprometida con el robo de información: malestar entre los empleados y daño de la imagen corporativa, lo que deriva en daños económicos que ahora sí se podrán cuantificar y que podrían afectar a la PyG.

Similarly, Information and employees are possibly the two most valuable assets of any company that too often are not correctly identified, assessed or quantified, and both assets suffer if the company’s security is compromised with the theft of information: employees discomfort and damage to corporate image, resulting in economic damage that now can be quantified and could affect the P&L.

Las escuelas de negocios hacen un buen trabajo formando líderes, pero con este artículo hago un llamamiento a que incorporen conceptos de seguridad y privacidad en su oferta académica para tener organizaciones más preparadas, de arriba abajo.

Business schools do a good work forming leaders but with this article I appeal to incorporate security and privacy concepts in their academic offerings to have more prepared organizations, from top to bottom.

— Simon Roses Femerling

Posted in Business, Economics, Hacking, Security, Technology | Tagged , , , | Leave a comment