Showing posts with label Reversing. Show all posts
Showing posts with label Reversing. Show all posts

Friday, February 13, 2015

[EXPLOITME] Nivel básico - #2 - Reconstrucción y análisis de código - exploitme-win.s (Spanish)


NOTE: If you want to read the post in English, please use the Google Translate button located on the right side of the page.

Un nuevo año, un nuevo reto y un nuevo Pwn. ]¬)

En esta ocasión el reto se trata de realizar la traducción de un listado de código en Lenguaje Ensamblador a código en Lenguaje "C", identificar la vulnerabilidad existente y aprovecharse de la misma para imprimir en pantalla un mensaje.

Bien, revisemos los puntos que se necesitan completar:

1. ¿Cuántas variables locales hay en la función main?
2. ¿De qué tipo son cada una de las variables locales identificadas en el punto anterior?
3. Detecta la vulnerabilidad existente en el código.
4. Define en qué condiciones exactas es posible explotarla.
5. Convierte a código C el codigo ASM y compílalo sin errores para conseguir el ejecutable final.
6. Explota el fallo y modifica el flujo del programa para que imprima por pantalla el siguiente mensaje "[*] Pwned!"
7. Propón correcciones para evitar la vulnerabilidad tanto en el código en C como en ASM

NOTA: Intentaré llevar en la secuencia que indican las preguntas, sin embargo, es probable que o salte puntos o toque ciertos temas antes de abordar por completo el objetivo de la pregunta.

Bien, sin más ni más, ¡al ataque!

Para empezar, hay que ponernos cómodos con respecto a nuestro objetivo a analizar. En este caso, demos un vistazo al código en Lenguaje Ensamblador para darnos una idea que como se encuentra compuesto y de igual modo, identificar puntos importantes que nos ayudarán en próximos pasos.



Ahora pasemos de lleno a la primera pregunta, la cual no es la primera de la lista, si no la quinta.

5.- Convierte a código C el codigo ASM y compílalo sin errores para conseguir el ejecutable final.

Después de un breve análisis, nos dimos cuenta que la estructura es muy intuitiva, es decir, es muy fácil de identificar los "pedazos" que se refieren a alguna rutina la cual ejecuta cierta acción y dará un resultado posterior. Las rutinas antes mencionadas son las que comienzan con un punto y la letra L (.L), los que tengan experiencia programando en Ensamblador se sentirán cómodos con esta estructura.

Ahora, para simplificar un poco la tarea del análisis, vamos a identificar las funciones utilizadas en el listado. Esta tarea la resolvemos fácilmente ya que las funciones inician con un "CALL".  Veamos...









Identificamos 5 funciones y nos podemos dar una idea de que se trata:

1. Hay un cálculo de tamaño de una string (strlen();)
2. Hay copiado de datos (strncpy(); y strcpy(); respectivamente) <- buffers? ]¬)
3. Las funciones (printf(); y puts();) muestran en pantalla datos

Para los que se encuentran familiarizados con la programación en lenguajes de alto nivel, sabrán que el llamado a una función es muy sencilla. Si requerimos imprimir en pantalla "ph33r" simplemente tenemos que hacer un printf("ph33r"); sin embargo, cuando dicha función es ejecutada, las instrucciones en ensamblador "internamente" ejecutan la función de manera distinta.

Veamos cómo se visualiza printf("ph33r"); en OllyDbg:



Ahora, veamos cómo se visualiza la función printf en el código ensamblador que tenemos:








Saturday, December 20, 2014

[EXPLOITME] Nivel básico - #1 - exploitme2-win.c (Spanish)

¡Saludos amigos!

Ya hacía tiempo que estaba un poco desconectado de varias cosas por cuestiones personales y laborales, sin embargo hace un par de días me encontraba monitoreando la lista de CLS me di cuenta que Boken (uno de sus integrantes) publicó un ExploitMe básico y haciendo un poco de espacio en mi apretada agenda me di a la tarea de crear este pequeño tute en el que explico su resolución paso a paso a mi modo y conforme a mis conocimientos y experiencia me lo permitan.

El ExploitMe objetivo se centra en la identificación de código fuente (HLL) en C y las instrucciones en Ensamblador que correspondan a dicho código. Para los que no tengan mucho skill en esta parte, les recomiendo MUCHO leer los tutoriales de Ricardo de "C y Reversing" así como la guía de Dennis Yurichev con nombre "Reverse Engineering for Beginners" y pueden descargar el libro de forma gratuita desde acá: http://beginners.re.

Considero que si es importante y además muy útil el poder hacer dicha "traducción" entre C y Ensamblador -y viceversa- ya que podrán tener una completa visibilidad acerca de lo que está sucediendo entre el programa y la máquina, ya sea que se encuentren debuggeando, desensamblando o lo que sea. Ya explicaré en algunos otros tutes lo que he aprendido sobre la marcha.

Regresando un poco al tute, les pido de favor que si encuentran algún error me lo hagan saber y con gusto arreglo el documento.

Habiendo dicho todo esto, ¡Al ataque!

Herramientas utilizadas:
Virtual Box (Windows XP SP2 32b - ESP)
Code::Blocks (Compilador)
Python
Immunity Debugger

Código del ExploitMe:



Bien, resolvamos el primer punto:

1. Compílalo, e identifica la dirección de las funciones main() y checkpass()

Utilizando Code::Blocks, prácticamente copiamos, pegamos y compilamos el código del ExploitMe. Posteriormente lo abrimos en el Immunity Debugger.

Ahora, nos saltamos (CTRL + G) directo al VA (401000) y le seteamos un BP.





Nos vamos instrucción por instrucción (F7) y llegaremos hasta 4010F8 que es la dirección hacia donde saltaremos al codigo que nos atañe (a la función que nos muestre el mensaje de "Access granted!"). Bien, le seteamos un BP de igual manera.





Si se preguntan la razón del por qué los BP's, siento que es bueno siempre estar parando en aquellos puntos clave en los cuales uno puede parar y darse una vuelta por el stack, el memory dump o lo que sea; por lo menos a mi me ha servido.

Si saltamos (ENTER) a ese CALL, entraremos prácticamente al main().

Vemos como desde la dirección 4013C0 hasta 401427 se encuentran las instrucciones relacionadas a la función main(). En la imagen siguiente se encuentra el stack frame de main, seleccionada en color azul.
























Sunday, October 20, 2013

CHR1X'S REVERSING CHALLENGE: vuln1.exe

Hello everyone,

I am here again, a little more active than the previous weeks. Now, I have a challenge for YOU. I've been very interesting for some time in Binary Analysis, as you may know this is not an easy task, and in order to complete such you must be able to understand C/ASM code mainly.


So, what's the challenge? The objective is not to trigger the vulnerability, in other words don't think that the target is to control EIP -which actually you can do it- but not for this case, instead, you should be able to describe the root cause of the vulnerability, how did you find it and the steps you found it using the tools of your election, say through a Debugger, IDA or whatever.

The target file is a simple executable that you can download from here:

http://www42.zippyshare.com/v/49161100/file.html

To have a most closer look about what I am expecting as a solving tutorial is something like this:

http://secunia.com/gfx/pdf/Binary_Analysis_813.pdf

I truly believe that these practices are very good to reinforce or learn new things related to binary analysis.

For those that join the challenge can send the solution to my mail. BTW, the submitted solutions will be published here.

Thursday, October 17, 2013

Binary Auditing Training Package - Vulnerability Analysis Challenges (stack4.exe) - ImmunityDebugger

Hello mates, I am back again! Yeah, ph33r! hehe

Now, I am releasing the new video-tuto for the solution of stack4.exe which is part of the "Vulnerability Analysis Challenges" from http://www.binary-auditing.com.

This one was particularly tricky, since it has little things related to control codes, specifically about the CRLF characters. Seemed to be that was the simple assignation to EAX we have seen on the previous challenges but IS NOT, instead, the party is starting since we now need to redirect the program's flow execution. Oh yeah baby!!!!11 ]¬)

As always, if you have any questions or comments, please feel free to send me anything you want to my e-mail address (chr1x@izpwning.me) or better post your comments on the YouTube channel.



Previous Solutions/Challenges:

STACK1 - http://chr1x.izpwning.me/2013/08/binary-auditing-training-package.html
STACK2 - http://chr1x.izpwning.me/2013/09/binary-auditing-training-package.html
STACK3 - http://chr1x.izpwning.me/2013/09/binary-auditing-training-package_22.html

Sunday, September 22, 2013

Binary Auditing Training Package - Vulnerability Analysis Challenges (stack3.exe) - ImmunityDebugger

Hello everybody,

Today I am showing the solution for the stack3.exe challenge, which as you may know is part of the "Vulnerability Analysis Challenges" from http://www.binary-auditing.com.

This one is very similar like the previous ones and I would like to suggest you to see the last video-tutos for stack{1,2}.exe in order to understand what I am doing in the next challenges.


Suggestions? Comments? Drop me an e-mail: chr1x@izpwning.me

Links: 
Binary Auditing Training Package (http://www.binary-auditing.com)

Friday, September 6, 2013

Binary Auditing Training Package - Vulnerability Analysis Challenges (stack2.exe) - ImmunityDebugger

Hello everybody,

This week I had a free time and I've worked on the next challenge stack2.exe of the "Vulnerability Analysis Challenges". This one was a very nice one, since seems very similar as the stack1.exe challenge, but this time we need to solve a little dirty trap. I can honestly say that I had a good time trying to solve this challenge.

For the new visitors, I would like to invite them to my previous video-tutorial in where I show the solution to the stack1.exe challenge. Through this way you can understand very well the new ones, since I am not explaining certain concepts that I already explained.


Suggestions? Comments? Drop me an e-mail: chr1x@izpwning.me

Links: 
Binary Auditing Training Package (http://www.binary-auditing.com)

Thursday, August 22, 2013

The Binary Auditing Training Package (chr1x's Walkthrough)

Some time ago, browsing the Internetz I found a very very nice resource for those who are interested in learning BA (Binary Analysis) using tools such as IDA Pro. This resource in a shape of a training package called "Free IDA Pro Binary Auditing Training Material for University Lectures". This training is a complete set of information along with different "challenges" (Crackme's and ReverseMe's sounds familiar?) which are included on the same package with the aim to test your new knowledge. Nasty, right?

Since I am a guy who LOVES challenges, I've decided to start solving the contained challenges as a self-learning practice. I am going to publish the challenges on a video format just to give you an easy and graphical view of the way I used to solve them.

It is good to mention that I am not just doing dead-code analysis using IDA, I am also planning to follow the flow through the dynamic part (using a Debugger) in order to get a good understanding about how to analyze -or use the tools- depending of the target/situation.

As soon as I complete each challenge, I will update this blog so I'd suggest you to subscribe to the blog and you can get noticed once new content is uploaded.

I am going to advance as my spare time permits, It's not a promise but I'll try to upload stuff in a regular manner.

Final words:

I would like to extend my gratitude to Dr. Thorsten Schneider for give us the opportunity to get access to such amazing resource FOR FREE.

Links:

The Binary Auditing Training / Official website: http://www.binary-auditing.com/
The Binary Auditing Training Package (zip file) can be obtained directly from here.
- Zip password: fdcd2ff4c2180329053650f3075d39f4
- MD5 Hash: c2b4720549b3410385087fa1b1e28bc7