Showing posts with label ImmunityDebugger. Show all posts
Showing posts with label ImmunityDebugger. 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.
























Tuesday, November 5, 2013

!apilookup - Win32 API Function Reference Locator for ImmunityDebugger

Hidey-ho everyone!

Well, after long time while I've been busy with a lot of stuff, finally I am back with a very nice goodie for you. As you have seen I am a big fan of ImmunityDebugger -but also of the old friend OllyDBG of course- and after some time I finally decided to put hands-on and make a plug-in.

Let me introduce you to the "!apilookup - Win32 API Function Reference Locator for ImmunityDebugger". The aim of this PyCommand is to provide quick access to Win32 API functions which are commonly required when performing debugging sessions. Yep!, NO MORE - Google => getprocaddress win32 api - Instead, on the ImmunityDebugger command bar just type this command: !apilookup getprocaddress and you will get direct-access to the required function. - Applauses!

Actually, one good point to note is the ability to provide not the whole word of a function, so you can do either !apilookup isdebuggerpresent or !apilookup isdebug, giving back the same results. RegEx r0x XD

For instance:


At this time I am pretty sure that you are wondering How The F**k I got the Win32.HLP as .CHM? Well, after a lot of time in searching Win32API.chm with no success, I've decided to make it. The support of .HLP files are no longer active for new versions of Windows, so many of the good old help files such as OllyDBG, ImmDBG and others are under this format. No PANIC. I've the CHM version for them too, but for a different post.

OK, so you know how the !apilookup works, this is how to get it. ]¬)

Installation steps:
  1. Download the package from my git repo here.
  2. Unrar and run the executable as Admin. - The exe looks malicious but it is not - promise. XD
  3. Open ImmunityDebugger and in the command bar type: !apilookup <function>
  4. Enjoy!
I know that there's an almost the same tool made by the master @MarioVilas, which offer on-line and updated references to APIs, so maybe you can use my "off-line" version when you don't have Inet access like my case when debugging on the bus or from any isolated location. 

That's all. Comment and share!

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)

Sunday, August 25, 2013

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

This is the first video I made for the "Binary Auditing Training Package" of http://www.binary-auditing.com. If you are already familiar with the package you'll see that it contains LOTS of challenges, and I decided to go to the chapter 10 "Vulnerability Analysis", no reason in particular; Basically because it sounds sexy. hehe.

Today, I am presenting the solution for the first challenge which consists basically in giving a solution for /010 - vulnerability analysis/01_warming_up_on_stack/stack1.exe of the package playing around with the stack through buffers using the ImmunityDebugger as a main tool. I am going to create the same solution but now using the IDA disassembler.

It is good to mention that all of the challenges for this chapter are the old Gera's InsecureProgramming challenges compiled as Windows executables. Originally, the researchers interested in source-code auditing can use those challenges -written in C- to understand how the code looks and then also identify/exploit such vulnerabilities contained within the code. Of course we can get the source for all the challenges, but we are good boys and we are not cheating and our target is to solve the challenges from a Reverse Code Engineering (RCE) perspective.

Said so, here the video:



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

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