Apuntes y recursos Reversing
Apuntes y toma de contacto con Cutter / radare2
Radare2 es una estupenda herramienta de desensamblado y analisis de aplicaciones.
Lo que se conoce como Reversing / Ingenieria inversa.
Cutter es un nuevo entorno grafico con Radare.
Lo que lo hace mucho mas intuitivo
Nota: Gracias a un compañero S0ftD4t que conoci en el congreso Navaja Negra Conference 2019 que me ha picado en el mundo de la Ingenieria Inversa.
Recuerda: En la categoria Apuntes Voy a poner apuntes y notas de los proyectos que tengo en marcha.
No son articulos conpletos.
Pero te pueden ayudar a resolver dudas , problemas y tener referencias.
Instalacion Cutter:
- cutter
https://cutter.re/
Ve a downloads y escoge la imagen que te propone:
(La pagina detecta automaticamente tu sistema operativo y te propone la imagen adecuada)
Instalacion Radare2:
Radare2 (debian) https://www.radare.org/n/
apt-get install radare2
Para actualizar a la ultima version:
Descargate e instala el paquete .deb de: https://radare.mikelloc.com/list
En mi caso: https://radare.mikelloc.com/get/4.0.0/radare2_4.0.0_amd64.debRadare2 (Windows 64)
Descargate y descomprime el paquete zip de https://radare.mikelloc.com/list
Para windows hay 2 versiones Librerias Visual c 2017 y Visual c 2015 Si dudas Prueba con las 2.
En mi caso:https://radare.mikelloc.com/get/4.0.0/radare2-vs2017_64-4.0.0.zip
La version con msvc no me funciono.
Abre un interprete de comandos ve a la carpeta donde has descomprimido el paquete. y ejecuta radare2.exe
Si te lias con el patch usa la version instalable: radare2_installer-vs2017_64.exeRadare2 (Windows 32)
Tendras que ir a una version antigua: (la ultima precompilada para 32bits es la 3.2.1)
https://radare.mikelloc.com/get/3.2.1/radare2-msvc_32-3.2.1.zip
https://radare.mikelloc.com/get/3.2.1/radare2_installer-msvc_32-3.2.1.exe
Instalacion IDE CodeBlocks:
Si no te importa que este en ingles
Es la opcion IDE mas ligera y portable. (no necesita intalacion).
CodeBlocks (debian/ubuntu/mint)
apt-get install Codeblocks xterm
CodeBlocks (windows) http://www.codeblocks.org/downloads/26
Si quieres un IDE en español prueba eclipse o devcpp
Compilacion hello word en C (linux)
Manual instalacion Compilacion con GCC (GNU Compiler Collection) (Linux/windows) https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html
1) creo el archivo hello_word.c : nano hello_word.c
// hello_word.c #include <stdio.h> int main() { printf("Hello, world!\n"); return 0; }
2) Compilo:
jejo@em50l:~/reversing/radare2$ gcc hello_word.c
3) Ejecuto:
jejo@em50l:~/reversing/radare2$ ./a.out Hello, world!
Analisis Clasico binario hello_word (comandos linux)
Informacion del binario: file a.out
jejo@em50l:~/reversing/radare2$ file a.out a.out: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=edc06b4ab81865d4f1ea8628f299e7363afc6937, not stripped
Informacion del ELF: readelf -a a.out
-a
puede dar Demasiada informacion dejo opcion -h
jejo@em50l:~/reversing/radare2$ readelf -h a.out Encabezado ELF: Mágico: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 Clase: ELF64 Datos: complemento a 2, little endian Versión: 1 (current) OS/ABI: UNIX - System V Versión ABI: 0 Tipo: DYN (Fichero objeto compartido) Máquina: Advanced Micro Devices X86-64 Versión: 0x1 Dirección del punto de entrada: 0x530 Inicio de encabezados de programa: 64 (bytes en el fichero) Inicio de encabezados de sección: 6448 (bytes en el fichero) Opciones: 0x0 Tamaño de este encabezado: 64 (bytes)
Analisis del uso de la memoria: file a.out
jejo@em50l:~/reversing/radare2$ size a.out text data bss dec hex filename 1516 600 8 2124 84c a.out jejo@em50l:~/reversing/radare2$
Busqued de “strings”/cadenas de texto (dentro del programa): strings a.out
jejo@em50l:~/reversing/radare2$ strings a.out /lib64/ld-linux-x86-64.so.2 libc.so.6 puts GLIBC_2.2.5 _ITM_registerTMCloneTable Hello, world! ;*3$" GCC: (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Ver que librerias utiliza: ldd a.out
jejo@em50l:~/reversing/radare2$ ldd a.out linux-vdso.so.1 (0x00007fff3036c000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f988bfeb000) /lib64/ld-linux-x86-64.so.2 (0x00007f988c5de000)
desensamblado: objdump -M intel -d a.out
jejo@medion:~/reversing/radare2/$ objdump -M intel -d a.out a.out: formato del fichero elf64-x86-64 Desensamblado de la sección .init: 00000000000004e8 <_init>: 4e8: 48 83 ec 08 sub rsp,0x8 4ec: 48 8b 05 f5 0a 20 00 mov rax,QWORD PTR [rip+0x200af5] # 200fe8 <__gmon_start__> 4f3: 48 85 c0 test rax,rax 4f6: 74 02 je 4fa <_init+0x12> 4f8: ff d0 call rax 4fa: 48 83 c4 08 add rsp,0x8 4fe: c3 ret
Analisis de ejecucion con ltrace: ltrace ./a.out
visualiza llamadas a las funciones de las librerias.
jejo@em50l:~/reversing/hello_word1$ ltrace ./a.out puts("Hello, world!"Hello, world! ) = 14 +++ exited (status 0) +++
Analisis de ejecucion con strace: strace -a80 ./a.out
En sistemas strace/procmon a veces es muy util para encontrar problemas en la ejecucion del archivo.
jejo@em50l:~/reversing/radare2$ strace -a80 ./a.out execve("./a.out", ["./a.out"], 0x7ffc9f32f9a8 /* 50 vars */) = 0 openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\3\0\0\3\0>\0\1\0\0\0\260\34\2\0\0\0\0\0"..., 832) = 832 mmap(NULL, 118098, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7ff355c5b000 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 write(1, "Hello, world!\n", 14Hello, world!) = 14 exit_group(0) = ? +++ exited with 0 +++
Analisis Clasico del binario hello_word
(comandos aplicacion radare2)
Esta vez lo hago con windows. Ya que windows no tiene comandos para obtener informacion de los ejecutables.
- Informacion del binario: rabin2.exe -I Hola_Mundo.exe
Aqui dejo la salida del programa compilado con code blocks.
C:\reversing\radare2-vs2017_64-4.0.0\bin>rabin2.exe -I Hola_Mundo_code_blocks.exe arch x86 baddr 0x400000 binsz 8704 bintype pe bits 32 canary false retguard false class PE32 cmp.csum 0x0000fcec compiled Thu Jan 1 01:48:01 1970 crypto false endian little havecode true hdr.csum 0x0000fcec laddr 0x0 lang c linenum true lsyms true machine i386 maxopsz 16 minopsz 1 nx false os windows overlay false pcalign 0 pic false relocs true signed false sanitiz false static false stripped true subsys Windows CUI va true
- imports del binario: rabin2.exe -I Hola_Mundo.exe
- Programa compilado con code blocks.
Se pueden ver las funciones C que utiliza y que librerias dll del sistema enlaza.
En este caso msvcrt.dll y KERNEL32.dll.
C:\reversing\radare2-vs2017_64-4.0.0\bin>rabin2.exe -i Hola_Mundo_code_blocks.exe [Imports] nth vaddr bind type name ----------------------------- 13 0x0040611c NONE FUNC msvcrt.dll_fwrite 14 0x00406120 NONE FUNC msvcrt.dll_memcpy 15 0x00406124 NONE FUNC msvcrt.dll_puts 17 0x0040612c NONE FUNC msvcrt.dll_vfprintf 3 0x004060c0 NONE FUNC KERNEL32.dll_ExitProcess 4 0x004060c4 NONE FUNC KERNEL32.dll_GetLastError 5 0x004060c8 NONE FUNC KERNEL32.dll_GetModuleHandleA 6 0x004060cc NONE FUNC KERNEL32.dll_GetProcAddress
- Comparo con el mismo codigo compilado con visual studio 2015.
Veo que cambian mucho las librerias utilizadas.
En este caso .NET Version: v4.0. y mscoree.dll.
C:\reversing\radare2-vs2017_64-4.0.0\bin>rabin2.exe -i hola_mundo_msvc.exe Metadata Signature: 0x268 0x10001424a5342 12 .NET Version: v4.0.30319 Number of Metadata Streams: 5 DirectoryAddress: 6c Size: 1cc Stream name: MZe 4 DirectoryAddress: 238 Size: 26c Stream name: MZe 4 DirectoryAddress: 73676e69 Size: 0 Stream name: MZe 4 DirectoryAddress: 18 Size: 535523 Stream name: MZe 4 DirectoryAddress: 10 Size: 49554723 Stream name: MZe 4 [Imports] nth vaddr bind type name ----------------------------- 1 0x00402000 NONE FUNC mscoree.dll__CorExeMain
- Compilado con el comando cl.exe (msvc build tools) (ver apendice)
veo como solo utiliza KERNEL32.dll
C:\reversing\radare2-vs2017_64-4.0.0\bin>rabin2.exe -i holamundo_cl.exe [Imports] nth vaddr bind type name ----------------------------- 1 0x00411000 NONE FUNC KERNEL32.dll_QueryPerformanceCounter 2 0x00411004 NONE FUNC KERNEL32.dll_GetCurrentProcessId 3 0x00411008 NONE FUNC KERNEL32.dll_GetCurrentThreadId 4 0x0041100c NONE FUNC KERNEL32.dll_GetSystemTimeAsFileTime 5 0x00411010 NONE FUNC KERNEL32.dll_InitializeSListHead 6 0x00411014 NONE FUNC KERNEL32.dll_IsDebuggerPresent 7 0x00411018 NONE FUNC KERNEL32.dll_UnhandledExceptionFilter 8 0x0041101c NONE FUNC KERNEL32.dll_SetUnhandledExceptionFilter 9 0x00411020 NONE FUNC KERNEL32.dll_GetStartupInfoW 10 0x00411024 NONE FUNC KERNEL32.dll_IsProcessorFeaturePresent 11 0x00411028 NONE FUNC KERNEL32.dll_GetModuleHandleW 12 0x0041102c NONE FUNC KERNEL32.dll_GetCurrentProcess 13 0x00411030 NONE FUNC KERNEL32.dll_TerminateProcess 14 0x00411034 NONE FUNC KERNEL32.dll_RtlUnwind 15 0x00411038 NONE FUNC KERNEL32.dll_GetLastError 16 0x0041103c NONE FUNC KERNEL32.dll_SetLastError 17 0x00411040 NONE FUNC KERNEL32.dll_EnterCriticalSection 18 0x00411044 NONE FUNC KERNEL32.dll_LeaveCriticalSection 19 0x00411048 NONE FUNC KERNEL32.dll_DeleteCriticalSection 20 0x0041104c NONE FUNC KERNEL32.dll_InitializeCriticalSectionAndSpinCount 21 0x00411050 NONE FUNC KERNEL32.dll_TlsAlloc 22 0x00411054 NONE FUNC KERNEL32.dll_TlsGetValue 23 0x00411058 NONE FUNC KERNEL32.dll_TlsSetValue 24 0x0041105c NONE FUNC KERNEL32.dll_TlsFree 25 0x00411060 NONE FUNC KERNEL32.dll_FreeLibrary 26 0x00411064 NONE FUNC KERNEL32.dll_GetProcAddress 27 0x00411068 NONE FUNC KERNEL32.dll_LoadLibraryExW 28 0x0041106c NONE FUNC KERNEL32.dll_GetStdHandle 29 0x00411070 NONE FUNC KERNEL32.dll_WriteFile 30 0x00411074 NONE FUNC KERNEL32.dll_GetModuleFileNameA 31 0x00411078 NONE FUNC KERNEL32.dll_MultiByteToWideChar 32 0x0041107c NONE FUNC KERNEL32.dll_WideCharToMultiByte 33 0x00411080 NONE FUNC KERNEL32.dll_ExitProcess 34 0x00411084 NONE FUNC KERNEL32.dll_GetModuleHandleExW 35 0x00411088 NONE FUNC KERNEL32.dll_GetCommandLineA 36 0x0041108c NONE FUNC KERNEL32.dll_GetCommandLineW 37 0x00411090 NONE FUNC KERNEL32.dll_GetACP 38 0x00411094 NONE FUNC KERNEL32.dll_HeapFree 39 0x00411098 NONE FUNC KERNEL32.dll_HeapAlloc 40 0x0041109c NONE FUNC KERNEL32.dll_CompareStringW 41 0x004110a0 NONE FUNC KERNEL32.dll_LCMapStringW 42 0x004110a4 NONE FUNC KERNEL32.dll_GetFileType 43 0x004110a8 NONE FUNC KERNEL32.dll_CloseHandle 44 0x004110ac NONE FUNC KERNEL32.dll_FindClose 45 0x004110b0 NONE FUNC KERNEL32.dll_FindFirstFileExA 46 0x004110b4 NONE FUNC KERNEL32.dll_FindNextFileA 47 0x004110b8 NONE FUNC KERNEL32.dll_IsValidCodePage 48 0x004110bc NONE FUNC KERNEL32.dll_GetOEMCP 49 0x004110c0 NONE FUNC KERNEL32.dll_GetCPInfo 50 0x004110c4 NONE FUNC KERNEL32.dll_GetEnvironmentStringsW 51 0x004110c8 NONE FUNC KERNEL32.dll_FreeEnvironmentStringsW 52 0x004110cc NONE FUNC KERNEL32.dll_SetEnvironmentVariableA 53 0x004110d0 NONE FUNC KERNEL32.dll_SetStdHandle 54 0x004110d4 NONE FUNC KERNEL32.dll_GetStringTypeW 55 0x004110d8 NONE FUNC KERNEL32.dll_GetProcessHeap 56 0x004110dc NONE FUNC KERNEL32.dll_FlushFileBuffers 57 0x004110e0 NONE FUNC KERNEL32.dll_GetConsoleCP 58 0x004110e4 NONE FUNC KERNEL32.dll_GetConsoleMode 59 0x004110e8 NONE FUNC KERNEL32.dll_HeapSize 60 0x004110ec NONE FUNC KERNEL32.dll_HeapReAlloc 61 0x004110f0 NONE FUNC KERNEL32.dll_SetFilePointerEx 62 0x004110f4 NONE FUNC KERNEL32.dll_WriteConsoleW 63 0x004110f8 NONE FUNC KERNEL32.dll_CreateFileW 64 0x004110fc NONE FUNC KERNEL32.dll_DecodePointer 65 0x00411100 NONE FUNC KERNEL32.dll_RaiseException
- Compilado con DevC++ TDM-GCC 64bits
veo como utiliza KERNEL32.dll y msvcrt.dll
C:\reversing\radare2-vs2017_64-4.0.0\bin> ./rabin2.exe -i Hola_Mundo_devc_TDM64.exe [Imports] nth vaddr bind type name ----------------------------- 1 0x004081ec NONE FUNC KERNEL32.dll_DeleteCriticalSection 2 0x004081f4 NONE FUNC KERNEL32.dll_EnterCriticalSection 3 0x004081fc NONE FUNC KERNEL32.dll_GetCurrentProcess 4 0x00408204 NONE FUNC KERNEL32.dll_GetCurrentProcessId 5 0x0040820c NONE FUNC KERNEL32.dll_GetCurrentThreadId 6 0x00408214 NONE FUNC KERNEL32.dll_GetLastError 7 0x0040821c NONE FUNC KERNEL32.dll_GetStartupInfoA 8 0x00408224 NONE FUNC KERNEL32.dll_GetSystemTimeAsFileTime 9 0x0040822c NONE FUNC KERNEL32.dll_GetTickCount 10 0x00408234 NONE FUNC KERNEL32.dll_InitializeCriticalSection 11 0x0040823c NONE FUNC KERNEL32.dll_LeaveCriticalSection 12 0x00408244 NONE FUNC KERNEL32.dll_QueryPerformanceCounter 13 0x0040824c NONE FUNC KERNEL32.dll_RtlAddFunctionTable 14 0x00408254 NONE FUNC KERNEL32.dll_RtlCaptureContext 15 0x0040825c NONE FUNC KERNEL32.dll_RtlLookupFunctionEntry 16 0x00408264 NONE FUNC KERNEL32.dll_RtlVirtualUnwind 17 0x0040826c NONE FUNC KERNEL32.dll_SetUnhandledExceptionFilter 18 0x00408274 NONE FUNC KERNEL32.dll_Sleep 19 0x0040827c NONE FUNC KERNEL32.dll_TerminateProcess 20 0x00408284 NONE FUNC KERNEL32.dll_TlsGetValue 21 0x0040828c NONE FUNC KERNEL32.dll_UnhandledExceptionFilter 22 0x00408294 NONE FUNC KERNEL32.dll_VirtualProtect 23 0x0040829c NONE FUNC KERNEL32.dll_VirtualQuery 1 0x004082ac NONE FUNC msvcrt.dll___C_specific_handler 2 0x004082b4 NONE FUNC msvcrt.dll___dllonexit 3 0x004082bc NONE FUNC msvcrt.dll___getmainargs 4 0x004082c4 NONE FUNC msvcrt.dll___initenv 5 0x004082cc NONE FUNC msvcrt.dll___iob_func 6 0x004082d4 NONE FUNC msvcrt.dll___lconv_init 7 0x004082dc NONE FUNC msvcrt.dll___set_app_type 8 0x004082e4 NONE FUNC msvcrt.dll___setusermatherr 9 0x004082ec NONE FUNC msvcrt.dll__acmdln 10 0x004082f4 NONE FUNC msvcrt.dll__amsg_exit 11 0x004082fc NONE FUNC msvcrt.dll__cexit 12 0x00408304 NONE FUNC msvcrt.dll__fmode 13 0x0040830c NONE FUNC msvcrt.dll__initterm 14 0x00408314 NONE FUNC msvcrt.dll__lock 15 0x0040831c NONE FUNC msvcrt.dll__onexit 16 0x00408324 NONE FUNC msvcrt.dll__unlock 17 0x0040832c NONE FUNC msvcrt.dll_abort 18 0x00408334 NONE FUNC msvcrt.dll_calloc 19 0x0040833c NONE FUNC msvcrt.dll_exit 20 0x00408344 NONE FUNC msvcrt.dll_fprintf 21 0x0040834c NONE FUNC msvcrt.dll_free 22 0x00408354 NONE FUNC msvcrt.dll_fwrite 23 0x0040835c NONE FUNC msvcrt.dll_malloc 24 0x00408364 NONE FUNC msvcrt.dll_memcpy 25 0x0040836c NONE FUNC msvcrt.dll_printf 26 0x00408374 NONE FUNC msvcrt.dll_signal 27 0x0040837c NONE FUNC msvcrt.dll_strlen 28 0x00408384 NONE FUNC msvcrt.dll_strncmp 29 0x0040838c NONE FUNC msvcrt.dll_vfprintf
- strings del binario: rabin2.exe -z Hola_Mundo.exe
- Programa compilado con code blocks.
es el que menos strings muestra.
C:\reversing\radare2-vs2017_64-4.0.0\bin> ./rabin2.exe -z Hola_Mundo_code_blocks.exe [Strings] nth paddr vaddr len size section type string ------------------------------------------------------- 0 0x00001400 0x00403000 13 14 .rdata ascii libgcj-16.dll 1 0x0000140e 0x0040300e 19 20 .rdata ascii _Jv_RegisterClasses 2 0x00001424 0x00403024 22 23 .rdata ascii Hola Mundo codeblocks! 3 0x00001440 0x00403040 23 24 .rdata ascii Mingw runtime failure:\n 4 0x00001458 0x00403058 48 49 .rdata ascii VirtualQuery failed for %d bytes at address %p 5 0x0000148c 0x0040308c 49 50 .rdata ascii Unknown pseudo relocation protocol version %d.\n 6 0x000014ec 0x004030ec 18 19 .rdata ascii GCC: (tdm-1) 5.1.0
- Programa compilado con Dev Cpp.
C:\reversing\radare2-vs2017_64-4.0.0\bin> ./rabin2.exe -z Hola_Mundo_devc_TDM64.exe [Strings] nth paddr vaddr len size section type string ------------------------------------------------------- 0 0x00002600 0x00404000 18 19 .rdata ascii hola mundo dev C++ 1 0x00002620 0x00404020 30 31 .rdata ascii Argument domain error (DOMAIN) 2 0x0000263f 0x0040403f 27 28 .rdata ascii Argument singularity (SIGN) 3 0x00002660 0x00404060 31 32 .rdata ascii Overflow range error (OVERFLOW) ....
Analisis estatico del codigo de un binario con radare2
En un solo comando:
teclear radare2 -c "aaaa;afl;v" a.out
jejo@medion:~/Escritorio/reversing/radare2$ radare2 -c "aaaa;afl;s main;v" a.out
Con la v
aparece el entorno visual:
Nota: el entorno Visual solo funciona con linux
en windows se ve pero los menus no reaccionan al pulsarlos con el raton.
File Settings Edit View Tools Search Emulate Debug Analyze Help Tab [1] [0x0000063a] ┌─────────────────────────────────────────────────────────────────────────┐-----------------------------------. │[X] Disassembly (pd) [Cache] Off │[X] Functions (afl) [Cache] Off | │ ┌ 23: int main (int argc, char **argv, char **envp); │ 0x00000530 1 42 entry| │ │ ; DATA XREF from entry0 @ 0x54d │ 0x00000560 4 50 -> 40 sym.d| │ │ 0x0000063a 55 push rbp │ 0x000005a0 4 66 -> 57 sym.r| │ │ 0x0000063b 4889e5 mov rbp, rsp │ 0x000005f0 5 58 -> 51 entry| │ │ 0x0000063e 488d3d9f0000. lea rdi, str.Hello__world │ 0x00000630 1 10 entry| │ │ 0x00000645 e8c6feffff call sym.imp.puts ;│ 0x000006d0 1 2 sym._| │ │ 0x0000064a b800000000 mov eax, 0 │ 0x000006d4 1 9 sym._| │ │ 0x0000064f 5d pop rbp │ 0x00000660 4 101 sym._| │ └ 0x00000650 c3 ret │ 0x0000063a 1 23 main | │ 0x00000651 662e0f1f8400. nop word cs:[rax + rax] │ 0x00000510 1 6 sym.i| │ 0x0000065b 0f1f440000 nop dword [rax + rax] │-----------------------------------. │ ┌ 101: sym.__libc_csu_init (int64_t arg1, int64_t arg2, int64_t arg3); │[X] Symbols (isq) [Cache] Off | │ │ ; arg int64_t arg1 @ rdi │ 0x00000238 0 .interp | │ │ ; arg int64_t arg2 @ rsi │ 0x00000254 0 .note.ABI-tag | │ │ ; arg int64_t arg3 @ rdx │ 0x00000274 0 .note.gnu.build-id | │ │ ; DATA XREF from entry0 @ 0x546 │ 0x00000298 0 .gnu.hash | │ │ 0x00000660 4157 push r15 │ 0x000002b8 0 .dynsym | │ │ 0x00000662 4156 push r14 │ 0x00000360 0 .dynstr | │ │ 0x00000664 4989d7 mov r15, rdx ;│ 0x000003e2 0 .gnu.version | │ │ 0x00000667 4155 push r13 │ 0x000003f0 0 .gnu.version_r | │ │ 0x00000669 4154 push r12 │ 0x00000410 0 .rela.dyn | └─────────────────────────────────────────────────────────────────────────┘-----------------------------------'
Menu View => Decompiler
Para los que no se manejan bien con los terminales guiados de texto.
Es como una ventana (dibujada con caracteres de texto) Pulsar con el raton sobre View y luego en Decompiler
Luego pico en 0x0000063a 1 23 main e intro en la parte/ventana que queramos ver completa.
Nota: las pestañas se pueden cerrar pulsando en [X].
y podemos poner la pestaña actual a pantalla completa pulsando espacio.
File Settings Edit View Tools Search Emulate Debug Tab [1] [0x0000063a]
┌───────────────────────────────────────────────────────────────────────────────┐
│[X] Decompiler (pdc) [Cache] On │
│ function main () { │
│ // 1 basic blocks │
│ │
│ loc_0x63a: │
│ │
│ //DATA XREF from entry0 @ 0x54d │
│ push rbp │
│ rbp = rsp │
│ rdi = ["Hello, world!" //0x6e4 ; str.Hello__world] ; const char *s │
│ │
│ int puts("Hello, world!") │
│ eax = 0 │
│ //rsp ; rsp │
│ return │
│ (break) │
│ │
└───────────────────────────────────────────────────────────────────────────────┘
Depuracion basica de hello_word con radare
En un solo comando:
teclear: radare2 -c "aaaa;afl;db main;dc;v" -d a.out
jejo@medion:~/reversing/radare2$ radare2 -c "aaaa;afl;db main;dc;v" -d a.out Process with PID 28979 started... = attach 28979 28979 bin.baddr 0x5556172ff000 Using 0x5556172ff000 asm.bits 64 [x] Analyze all flags starting with sym. and entry0 (aa) [Warning: Invalid range. Use different search.in=? or anal.in=dbg.maps.x Warning: Invalid range. Use different search.in=? or anal.in=dbg.maps.x [x] Analyze function calls (aac) [x] Analyze len bytes of instructions for references (aar)
con v
aparecera el entorno visual con el programa arrancado y un breakpoin en la funcion main:
Nota: el entorno Visual solo funciona con linux
en windows se ve pero los menus no reaccionan al pulsarlos con el raton.
File Settings Edit View Tools Search Emulate Debug Analyze Help Tab [1] [0x5556172ff63a]
┌─────────────────────────────────────────────────────────────────────────┐-----------------------------------.
│[X] Disassembly (pd) [Cache] Off │[X] Stack (pxq 256@r:[Cache] Off |
│ ;-- rax: │ 0x7ffc44f1de88 0x00007f8f8a37ab97|
│ ;-- rip: │ 0x7ffc44f1de98 0x00007ffc44f1df68|
│ ┌ 23: int main (int argc, char **argv, char **envp); │ 0x7ffc44f1dea8 0x00005556172ff63a|
│ │ ; DATA XREF from entry0 @ 0x5556172ff54d │ 0x7ffc44f1deb8 0xaf1a475dbc25b9c8|
│ │ 0x5556172ff63a b 55 push rbp │ 0x7ffc44f1dec8 0x00007ffc44f1df60|
│ │ 0x5556172ff63b 4889e5 mov rbp, rsp │ 0x7ffc44f1ded8 0x0000000000000000|
│ │ 0x5556172ff63e 488d3d9f0000. lea rdi, str.Hello__world│ 0x7ffc44f1dee8 0xfaa97d6d067bb9c8|
│ │ 0x5556172ff645 e8c6feffff call sym.imp.puts ;│ 0x7ffc44f1def8 0x0000000000000000|
│ │ 0x5556172ff64a b800000000 mov eax, 0 │ 0x7ffc44f1df08 0x00007f8f8a75a733|
│ │ 0x5556172ff64f 5d pop rbp │ 0x7ffc44f1df18 0x000000000005f5d2|
│ └ 0x5556172ff650 c3 ret │-----------------------------------.
│ 0x5556172ff651 662e0f1f8400. nop word cs:[rax + rax] │[X] Registers (dr) [Cache] Off |
│ 0x5556172ff65b 0f1f440000 nop dword [rax + rax] │ rax = 0x5556172ff63a |
│ ;-- rcx: │ rbx = 0x00000000 |
│ ;-- rbp: │ rcx = 0x5556172ff660 |
└─────────────────────────────────────────────────────────────────────────┘-----------------------------------'
Tambien podemos probar con: radare2 -c "aaaa;afl;db main;dc;v" -d a.out
Analisis estatico hello_word con radare (paso a paso)
Paso a Paso
Teclear los siguientes comandos:
1) radare2 a.out
2) aaa
(analizar) 3https://ciberseguridad.blog/author/ricardo-narvaja/) afl
(listar funciones) 4) s main
(saltar a main) 5) pdf
desensamblar funcion
jejo@em50l:~/reversing/radare2$ radare2 a.out [0x00000530]> aaaa [Cannot analyze at 0x00000520g with sym. and entry0 (aa) [x] Analyze all flags starting with sym. and entry0 (aa) [Cannot analyze at 0x00000520ac) [x] Analyze function calls (aac) [x] Analyze len bytes of instructions for references (aar) [x] Check for objc references [x] Check for vtables [x] Type matching analysis for all functions (aaft) [x] Propagate noreturn information [x] Use -AA or aaaa to perform additional experimental analysis. [x] Finding function preludes [x] Enable constraint types analysis for variables [0x00000530]> afl 0x00000530 1 42 entry0 0x00000560 4 50 -> 40 sym.deregister_tm_clones 0x000005a0 4 66 -> 57 sym.register_tm_clones 0x000005f0 5 58 -> 51 entry.fini0 0x00000630 1 10 entry.init0 0x000006d0 1 2 sym.__libc_csu_fini 0x000006d4 1 9 sym._fini 0x00000660 4 101 sym.__libc_csu_init 0x0000063a 1 23 main 0x00000510 1 6 sym.imp.puts 0x000004e8 3 23 sym._init 0x00000000 3 97 -> 123 loc.imp._ITM_deregisterTMCloneTable [0x00000530]> s main [0x0000063a]> pdf ┌ 23: int main (int argc, char **argv, char **envp); │ ; DATA XREF from entry0 @ 0x54d │ 0x0000063a 55 push rbp │ 0x0000063b 4889e5 mov rbp,rsp │ 0x0000063e 488d3d9f0000. lea rdi,str.Hello__world ;0x6e4;"Hello, world!";const char *s │ 0x00000645 e8c6feffff call sym.imp.puts ;int puts(const char *s) │ 0x0000064a b800000000 mov eax, 0 │ 0x0000064f 5d pop rbp └ 0x00000650 c3 ret
Pulsamos v
(entorno visual)
Y ya tenemos menus , ponemos cambiar vistas y navegar con las flechas y el raton.
Nota: el entorno Visual solo funciona con linux
File Settings Edit View Tools Search Emulate Debug Analyze Tab [1] ┌──────────────────────────────────────────────────────────────────────────────────┐ │[X] Disassembly (pd) [Cache] Off │ │ ┌ 23: int main (int argc, char **argv, char **envp); │ │ │ ; DATA XREF from entry0 @ 0x54d │ │ │ 0x0000063a 55 push rbp │ │ │ 0x0000063b 4889e5 mov rbp, rsp │ │ │ 0x0000063e 488d3d9f0000. lea rdi, str.Hello__world ; 0x6e4 ; "Hello│ │ │ 0x00000645 e8c6feffff call sym.imp.puts ;[1] ; int puts(c│ │ │ 0x0000064a b800000000 mov eax, 0 │ │ │ 0x0000064f 5d pop rbp │ │ └ 0x00000650 c3 ret │ └──────────────────────────────────────────────────────────────────────────────────┘
Menu View => Decompiler
File Settings Edit View Tools Search Emulate Debug Tab [1] [0x0000063a]
┌───────────────────────────────────────────────────────────────────────────────┐
│[X] Decompiler (pdc) [Cache] On │
│ function main () { │
│ // 1 basic blocks │
│ │
│ loc_0x63a: │
│ │
│ //DATA XREF from entry0 @ 0x54d │
│ push rbp │
│ rbp = rsp │
│ rdi = ["Hello, world!" //0x6e4 ; str.Hello__world] ; const char *s │
│ │
│ int puts("Hello, world!") │
│ eax = 0 │
│ //rsp ; rsp │
│ return │
│ (break) │
│ │
└───────────────────────────────────────────────────────────────────────────────┘
Como se puede apreciar con este menu casi “clava el codigo en C“
Menu View => Decompiler with offsets
File Settings Edit View Tools Search Emulate Debug Analyze Help Tab [1] [0x0000063a]
┌──────────────────────────────────────────────────────────┐──────────────────────────────────────────────────┐
│[X] Decompiler With Offsets (pddo) [Cache] On │[X] Decompiler (pdc) [Cache] On │
│ ;-- rip: │ function main () { │
│ ┌ 23: int main (int argc, char **argv, char **envp); │ // 1 basic blocks │
│ │ ; DATA XREF from entry0 @ 0x54d │ │
│ │ 0x0000063a 55 push rbp │ loc_0x63a: │
│ │ 0x0000063b 4889e5 mov rbp, rsp │ │
│ │ 0x0000063e 488d3d9f0000. lea rdi, str.H│ //DATA XREF from entry0 @ 0x54d │
│ │ 0x00000645 e8c6feffff call sym.imp.p│ push rbp │
│ │ 0x0000064a b800000000 mov eax, 0 │ rbp = rsp │
│ │ 0x0000064f 5d pop rbp │ rdi = ["Hello, world!" //0x6e4 ; str.He│
│ └ 0x00000650 c3 ret │ │
│ 0x00000651 662e0f1f8400. nop word cs:[r│ int puts("Hello, world!") │
│ 0x0000065b 0f1f440000 nop dword [rax│ eax = 0 │
│ ┌ 101: sym.__libc_csu_init (int64_t arg1, int64_t arg2, i│ //rsp ; rsp │
│ │ ; arg int64_t arg1 @ rdi │ return │
│ │ ; arg int64_t arg2 @ rsi │ (break) │
│ │ ; arg int64_t arg3 @ rdx │ │
│ │ ; DATA XREF from entry0 @ 0x546 │ } │
└──────────────────────────────────────────────────────────┘──────────────────────────────────────────────────┘
Con esto consigo dejar a la izquierda el codigo en ensamblador y a la derecha la interpretacion en c del mismo.
Referencias
https://www.radare.org/n/
https://radare.gitbooks.io/radare2book/content/tools/rabin2/strings.htmlhttps://fwhibbit.es/introduccion-reversing-0x00-introduccion
https://fwhibbit.es/introduccion-reversing-0x01-introduccionRicardo Narvaja
http://ricardonarvaja.info/WEB/RADARE/
https://ciberseguridad.blog/author/ricardo-narvaja/GCC and Make Compiling, Linking and Building C/C++ Applications
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.htmlCodeBlocks http://www.codeblocks.org/
https://www3.ntu.edu.sg/home/ehchua/programming/howto/CodeBlocks_HowTo.htmlEclipse IDE https://www.eclipse.org/downloads/packages/
Visual Studio Community https://visualstudio.microsoft.com/es/vs/community/
Visual Studio 2019 https://visualstudio.microsoft.com/downloads/
https://visualstudio.microsoft.com/es/vs/older-downloads/
https://docs.microsoft.com/en-us/visualstudio/install/create-an-offline-installation-of-visual-studio?view=vs-2019Visual Studio 2015 Community Edition (FREE) https://go.microsoft.com/fwlink/?LinkId=532606&clcid=0x409 (web) https://go.microsoft.com/fwlink/?LinkId=615448&clcid=0x409 (iso) https://docs.microsoft.com/en-us/visualstudio/install/create-an-offline-installation-of-visual-studio?view=vs-2015
ejemplos sencillos en c
https://www.tutorialgateway.org/c-programming-examples/ https://www.dotnetperls.com/Use the Microsoft C++ toolset from the command line https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=vs-2015 https://docs.microsoft.com/en-us/cpp/build/reference/c-cpp-building-reference?view=vs-2015
ejemplos en c# https://www.dotnetperls.com/
- Fundación Sadosky (ejercicios explotación de vulnerabilidades) https://github.com/fundacion-sadosky/abopp https://github.com/fundacion-sadosky/guia-escritura-exploits
Ejercicios/practicas con radare2 https://radare.gitbooks.io/radare2book/content/crackmes/ioli/intro.html https://dustri.org/b/defeating-ioli-with-radare2.html https://dustri.org/b/defeating-ioli-with-radare2-in-2017.html https://dustri.org/b/defeating-lincrackme3-with-radare2.html https://dustri.org/b/files/IOLI-crackme.tar.gz mas: abre https://dustri.org/b/archives.html y busca radare. https://www.megabeets.net/a-journey-into-radare-2-part-2/
Libro Reverse Engineering for Beginners https://beginners.re/RE4B-EN.pdf
- Libros de ingenieria inversa https://beginners.re/ (1080 paginas) https://beginners.re/RE4B-EN.pdf
Apendices
Entornos de compilacion Windows/Linux
Compilacion hello word en C (Windows con Microsoft Visual C++ Build Tools)
Documentacion Oficial:
https://docs.microsoft.com/en-us/cpp/build/walkthrough-compile-a-c-program-on-the-command-line?view=vs-2015
Para instalar un entorno de compilacion minimo.(“Microsoft Build Tools”)
puedes usar Microsoft C++ Build Tools 2015
Windows 7 necesita .NET Framework >4.5.1
Nota: Este enlace me ha costado sudor. he tenido que sacar el enlace del codigo fuente de: https://github.com/felixrieseberg/windows-build-tools
Para instalar un entorno mas completo: Visual Studio Community (Ojo 12Gb)
Si eres mas de software libre: (mas ligero)
- Orwell Dev-C++ (recomiendo: Dev-Cpp MinGW portable(38Mb) y Dev-Cpp TDM-GCC Portable(41Mb))
- CodeBlocks (recomiendo: mingw-nosetup.zip 90Mb )
- Eclipse IDE (Recomiendo: Eclipse Cpp Mars 170Mb )
- Si no quieres de IDE y eres mas de comandos: GCC/MinGW (GNU Compiler Collection) (Linux/windows)
Crear el archivo hello.c
En el ejemplo lo creo en la carpeta c:\kits\reversing
// hello.c #include <stdio.h> int main() { printf("Hello, world!\n"); return 0; }
Compilacion desde linea de comandos. (Paso a Paso).
Teclear los siguientes comandos:
Arrancar Visual C++ 2015 X86/X64 Build Tools Command Prompt
c:\Program Files\Microsoft Visual C++ Build Tools\vcbuildtools.bat
Para configurar el entorno de compilacion.cd c:\kits\reversing
Para ir a la carpeta del archivo.cl hello_word.c
para compilar el archivo hello_world.c y crear hello_word.exehello_word.exe
Para probar que el programa.
c:\>"c:\Program Files\Microsoft Visual C++ Build Tools\vcbuildtools.bat" c:\Program Files\Microsoft Visual C++ Build Tools>cd c:\kits\reversing c:\kits\reversing>cl hello_word.c Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24210 for x86 Copyright (C) Microsoft Corporation. All rights reserved. hello_word.c Microsoft (R) Incremental Linker Version 14.00.24210.0 Copyright (C) Microsoft Corporation. All rights reserved. /out:hello_word.exe hello_word.obj c:\kits\reversing>hello_word.exe hola Mundo
Si quieres mas programas sencillos para compilar y desensamblar:
https://www.tutorialgateway.org/c-programming-examples/