elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  ASM (Moderador: Eternal Idol)
| | | |-+  Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)  (Leído 4,070 veces)
harry_the_blogger

Desconectado Desconectado

Mensajes: 105


Visita mi blog es enriquemesa.blogspot.com


Ver Perfil WWW
Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« en: 14 Septiembre 2014, 03:51 am »

Hola, estoy desarrollando un programa. El programa busca las APIs sin usar la import table, él programa usa GetProcAddress y LoadLibrary para encontrar todas las APIs que necesita. Pero hay un problema: NO LLAMA A MI EXCEPTION HANDLER CUANDO HAY UNA EXCEPCION!!

El codigo, debería mostrar un mensaje "Exception catched!!" cuando haya una excepcion. Pero el programa sale sin más, aunque curiosamente, no crashea. Aún así la idea es que llame a mi manejador de excepciones, cosa que no hace

Aquí está mi codigo. Está escrito en FASM

Código
  1.  
  2.  
  3. format pe console 4.0
  4.  
  5. section '.text' readable writable executable
  6.  
  7. start:
  8.    call delta_offset       ;Calculates the delta offset
  9.  
  10. delta_offset:
  11.    pop ebp                 ;Save the current address of the delta_offset routine in memory
  12.    sub ebp, delta_offset   ;Current address of delta_offset ´- address of delta_offset at compilation time
  13.                            ;is equal to current address of virus body in memory. Now we can access any part of
  14.                            ;data embebbed in the code using [ebp+variable]
  15.  
  16. finding_kernel32:
  17. mov ebx, [FS : 0x30]        ;FS:0x30 is a pointer to the address of Process Environment Block (PEB)
  18.                                ;Now the Base Pointer (BX) points to the address of PEB in memory
  19.  
  20. mov ebx, [ebx + 0x0C]       ;Now we move 0x0C (12 bytes) from the address of PEB
  21.                                ;We get the value of ebx+0x0c, in other words, the address that has the PEB->Ldr pointer
  22.  
  23.                                ;Now we are in Ldr structure. We move the ebx pointer following the address in the
  24.                                ;PEB->Ldr pointer.
  25.  
  26. mov ebx, [ebx + 0x14]       ; get PEB->Ldr.InMemoryOrderModuleList.Flink (1st entry)
  27. mov ebx, [ebx]            ;2nd Entry
  28. mov ebx, [ebx]            ;3rd Entry
  29. mov ebx, [ebx + 0x10]   ; Get Kernel32 Base
  30. mov [ebp+dwKernelBase] , ebx
  31. add ebx, [ebx+0x3C] ; Start of PE header
  32. mov ebx, [ebx+0x78] ; RVA of export dir
  33. add ebx, [ebp+dwKernelBase]  ; VA of export dir
  34. mov [ebp+dwExportDirectory] , ebx
  35.  
  36. finding_address_of_getprocaddress:
  37. lea edx,[ebp+api_GetProcAddress]    ;Load in ebp the address of the API function name.
  38. mov ecx,[ebp+len_GetProcAddress]    ;Load in ecx the size of the API function name
  39.  
  40. call GetFunctionAddress           ;Call GetFunctionAddress
  41.  
  42. mov [ebp+AGetProcAddressA] , eax    ;The API function address in memory was stored by the
  43.                                        ;GetFunctionAddress function in eax, now we save the address
  44.                                        ;of the GetProcAddress in a variable for later use.
  45.  
  46. finding_address_of_loadlibrary:
  47. lea edx,[ebp+api_LoadLibrary]       ;Load in edx the API function name of LoadLibrary
  48. push edx                            ;edx could be a parameter for an API
  49. push dword [ebp+dwKernelBase]       ;save in the stack the address of the kernel32 library
  50.                                        ;dwKernelBase is used as handle
  51. call eax                            ;Calls a function by its address (eax stores it)
  52.                                        ;Could be GetProcAddress because in the instruction in
  53.                                        ;the line 39 it moves the address of that API from eax
  54.                                        ;and eax has no changes until 47 line.
  55. loading_required_libraries:
  56. mov [ebp+ALoadLibraryA] , eax       ;The last function could return the address of LoadLibrary in
  57.                                        ;in eax. eax register could be used by the last function as a
  58.                                        ;return value.
  59.  
  60.                                        ;Now the eax register contains the address of LoadLibrary
  61. lea edx , [ebp+szUser32]            ;Loads in edx, the library name of User32.dll
  62. push edx                            ;Put the edx value in the stack as a parameter for LoadLibrary
  63.                                        ;I believe that the function could be LoadLibrary because
  64.                                        ;it is an API that requires a string that contains the name of
  65.                                        ;the library that you want to load.
  66. call eax                            ;Call LoadLibrary API
  67.  
  68.    mov [ebp+hUser32], eax
  69.  
  70. finding_addresses_of_apis:
  71.  
  72. lea edx , [ebp+api_MessageBoxA]     ;Loads in edx the address of the name of MessageBoxA API
  73. push edx                            ;Put the name of MessageBoxA as a parameter for a function
  74. push eax                            ;I belive that eax is a handle to the loaded library
  75. mov ebx,[ebp+AGetProcAddressA]      ;Moves to ebx the address of GetProcAddressA
  76. call ebx                            ;Invokes GetProcAddressA using its address
  77.  
  78. mov [ebp+AMessageBoxAA] , eax       ;The last function (could be GetProcAddressA) returns the address of
  79.                                        ;MessageBoxA in eax. We move the address of that API to a variable for
  80.                                        ;later use.
  81.  
  82.                                        ;We start to search for functions inside
  83.                                        ;kernel32.dll
  84. set_exception_handler:
  85.    ;A simple way to set a exception handler, avoiding the
  86.    ;use of APIs that increase the size of the release.
  87.    push exception_handler
  88.    push dword [FS:0]
  89.    mov  [FS:0], esp
  90.  
  91. main:
  92.    push 0                              ;Put the HWND parameter
  93. lea edx,[ebp+szTitle]               ;Put the caption of the MessageBox
  94. push edx
  95. lea edx,[ebp+szMsg]                 ;Put the message body of the MessageBox
  96. push edx
  97. push 0                              ;Buttons type (For example MB_OK)
  98. call dword [ebp+AMessageBoxAA]          ;Calls MessageBoxA API
  99.  
  100. ;The following code tries to make many exceptions
  101. int3    ;Software breakpoints
  102. int3
  103. int3
  104. mov esi, 0  ;Access violation
  105. mov dword [esi], "fail"
  106.  
  107. exit:
  108.  
  109. ret
  110. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  111. ;  <<<<< GetFunctionAddress >>>>>> ;
  112. ; Extracts Function Address From Export Directory and returns it in eax   ;
  113. ; Parameters :  Function name in edx , Length in ecx  ;
  114. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  115.  
  116. GetFunctionAddress:
  117. push ebx    ;Save status of registers before execute the subroutine
  118. push esi    ;to preserve its content. It could make some errors to the
  119. push edi    ;caller function if modify the values that are common to the whole
  120.                ;program
  121.  
  122. mov esi, [ebp+dwExportDirectory]
  123. mov esi, [esi+0x20] ;RVA of ENT
  124. add esi, [ebp+dwKernelBase]  ;VA of ENT
  125. xor ebx,ebx
  126. cld
  127.  
  128. looper:
  129.  inc ebx
  130.  lodsd     ;Load a byte from the string pointed by SI into al register
  131.  add eax , [ebp+dwKernelBase]   ;eax now points to the string of a function
  132.  push esi ;preserve it for the outer loop
  133.  mov esi,eax
  134.  mov edi,edx
  135.  cld       ;The direction flag is clear, this means that the SI and DI pointers are
  136.                    ;incremented. (The instructions works to the forward direction)
  137.  
  138.  push ecx  ;Save ecx. Why?? The next instruction named "repe" decrements the counter.
  139.                    ;Because the ecx contains the length of the API name, we need to save it.
  140.                    ;In other parts of subroutine the program uses ecx register to compare the function
  141.                    ;with the kernel export table.
  142.  
  143.  repe cmpsb ;Compare each byte of the array pointed by DS:SI with the array pointed by ES:DI
  144.                     ;Repeat until the counter is not equal to zero, in other words,
  145.                     ;it only stops when it find a difference or the counter reachs the end of the string
  146.  
  147.  pop ecx   ;Pop the length of the string, and put it in the counter for another loop if it's needed
  148.  pop esi   ;Pop the last stack variable, and put it in esi.
  149.  jne looper
  150.  
  151.  dec ebx
  152.  mov eax,[ebp+dwExportDirectory]
  153.  mov eax,[eax+0x24]   ;RVA of EOT
  154.  add eax,[ebp+dwKernelBase] ;VA of EOT
  155.  movzx eax , word [ebx*2+eax] ;eax now holds the ordinal of our function
  156.  mov ebx,[ebp+dwExportDirectory]
  157.  mov ebx,[ebx+0x1C]   ;RVA of EAT
  158.  add ebx,[ebp+dwKernelBase] ;VA of EAT
  159.  mov ebx,[eax*4+ebx]
  160.  add ebx,[ebp+dwKernelBase]
  161.  mov eax,ebx
  162.  
  163. pop edi     ;Restore the registers to avoid generate a problem
  164. pop esi     ;in the caller function.
  165. pop ebx
  166. ret
  167.  
  168. exception_handler:
  169.    push 0                              ;Put the HWND parameter
  170. lea edx,[ebp+szTitle]               ;Put the caption of the MessageBox
  171. push edx
  172. lea edx,[ebp+szMsgException]                 ;Put the message body of the MessageBox
  173. push edx
  174. push 0                              ;Buttons type (For example MB_OK)
  175. call dword [ebp+AMessageBoxAA]          ;Calls MessageBoxA API
  176.  
  177. ret
  178. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  179. ; Data Shit ;
  180. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  181. szMsgException db 'Exception catched!!', 0
  182. api_ExitProcess dd 0
  183.  
  184. szTitle:  db  "From the heaven",0
  185. szMsg: db "Greetings from hell",0
  186. szUser32 db  "User32.dll",0
  187. hUser32             dd 0
  188. AGetProcAddressA:   dd  0
  189. api_GetProcAddress:   db  "GetProcAddress"
  190. len_GetProcAddress:   dd  $-api_GetProcAddress
  191. ALoadLibraryA: dd  0
  192. api_LoadLibrary:   db  "LoadLibraryA",0
  193. AMessageBoxAA: dd  0
  194. api_MessageBoxA:   db  "MessageBoxA",0
  195. dwKernelBase: dd  0
  196. dwExportDirectory:   dd  0
  197.  

Intenté hacer el siguiente método:

Código
  1. push exception_handler
  2.    push dword [FS:0]
  3.    mov  [FS:0], esp
  4.  

El metodo que describí funciona en este pequeño ejemplo (no es la aplicacion que estoy escribiendo):

Código
  1. format pe console 4.0 ;on 'dos_stub.exe'
  2. include 'C:\fasm\INCLUDE\WIN32AX.inc'
  3.  
  4. .data
  5.    msg_caption db 'SEH handler', 0
  6.    msg_exception db 'I catched an exception!! Amazing!!', 0
  7.  
  8. .code
  9.  
  10. main:
  11.    ;A simple way to set a exception handler, avoiding the
  12.    ;use of APIs that increase the size of the release.
  13.    push exception_handler
  14.    push dword [FS:0]
  15.    mov  [FS:0], esp
  16.  
  17.    mov esi, 0
  18.    mov dword [esi], "Pwnd"
  19.  
  20. exit:
  21.    invoke ExitProcess, 0
  22.  
  23. exception_handler:
  24.    invoke MessageBox, NULL, addr msg_exception, addr msg_caption, MB_OK
  25.    jmp exit
  26.    ret
  27.  
  28. .end main
  29.  
  30.  

Por que en el primer codigo no trabaja, mientras que en el segundo si lo hace??? Alguien puede decirme porqué??? Gracias de antemano, y perdon por hacerlos leer tanto. (XD).

Ah, se me olvidaba, también intenté usar SetUnhandledExceptionFilter (API) para establecer mi funcion como manejador de excepciones, pero no funciono. ¿Será qué el uso que le doy a ciertos registros afecta lo que trato de hacer??


« Última modificación: 14 Septiembre 2014, 04:02 am por harry_the_blogger » En línea

Vista mi blog es enriquemesa.blogspot.com
Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.935


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« Respuesta #1 en: 14 Septiembre 2014, 16:46 pm »

Tenes que aprender a depurar tu codigo, es un trabajo arduo y mucho mas para quien no lo escribio.

Estas confundido, si que es llamado tu exception handler, si pones un breakpoint en el mismo lo veras. EBP no tiene el valor que vos esperas ... y no hay ninguna garantia de que lo fuera a tener.


En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
harry_the_blogger

Desconectado Desconectado

Mensajes: 105


Visita mi blog es enriquemesa.blogspot.com


Ver Perfil WWW
Re: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« Respuesta #2 en: 14 Septiembre 2014, 19:17 pm »

Gracias Eternal Idol.
« Última modificación: 14 Septiembre 2014, 19:39 pm por harry_the_blogger » En línea

Vista mi blog es enriquemesa.blogspot.com
daryo


Desconectado Desconectado

Mensajes: 1.070



Ver Perfil WWW
Re: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« Respuesta #3 en: 14 Septiembre 2014, 19:34 pm »

Citar
??? Será que si guardo el valor de ebp en una variable, antes de que ocurra la excepcion, podré usarlo para llamar las APIs???

mm veo un fallo en eso porque [ebp + direccion de la variable] te da la direccion pero si tienes una variable en ves de ebp como sabes donde  estara esa variable donde guarda esa direccion?
En línea

buenas
harry_the_blogger

Desconectado Desconectado

Mensajes: 105


Visita mi blog es enriquemesa.blogspot.com


Ver Perfil WWW
Re: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« Respuesta #4 en: 14 Septiembre 2014, 19:41 pm »

Hola daryo. Tienes razón. Será que me puedes decir alguna forma de preservar ebp sin usar variables??? O será que hay forma de acceder al último valor que tenían los registros antes de morir??

Estaría muy agradecido si me dijeras como puedo preservar ebp. También investigaré  más sobre SEH con google. Gracias por tu ayuda, daryo

[Nuevo]
Tengo otra idea, ¿Será que es posible usar el truco del delta offset para referenciar las variables de nuevo? Lo intentaré. Les comentaré los resultados.
« Última modificación: 14 Septiembre 2014, 19:43 pm por harry_the_blogger » En línea

Vista mi blog es enriquemesa.blogspot.com
Danyfirex


Desconectado Desconectado

Mensajes: 493


My Dear Mizuho


Ver Perfil
Re: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« Respuesta #5 en: 15 Septiembre 2014, 21:31 pm »

si quieres preservar alguna variable puedes usar el stack.

push ebp ;guardas.
pop ebp ;lo agarras.

Saludos
En línea

harry_the_blogger

Desconectado Desconectado

Mensajes: 105


Visita mi blog es enriquemesa.blogspot.com


Ver Perfil WWW
Re: Problema al atrapar excepcion en ensamblador cambiando [fs:0] manualmente (FASM)
« Respuesta #6 en: 16 Septiembre 2014, 04:02 am »

si quieres preservar alguna variable puedes usar el stack.

push ebp ;guardas.
pop ebp ;lo agarras.

Saludos

Gracias Danyfirex. Disculpa, tengo una duda: ¿Puede corromperse la pila? Es decir, ¿que yo no sea capaz de recuperar los valores que tenía? Yo, hasta ahora, he creído que puede corromperse. Por eso intenté solucionarlo calculando el delta offset. Pero si me aclaras bien mi duda, usaré mejor tu codigo.

En línea

Vista mi blog es enriquemesa.blogspot.com
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Problema al controlar excepcion en Visual Studio « 1 2 3 »
.NET (C#, VB.NET, ASP)
Skeletron 29 24,488 Último mensaje 2 Febrero 2010, 03:34 am
por seba123neo
[problema] SOCKET EN FASM
ASM
afdlkglfgfdgfhgf 1 3,519 Último mensaje 29 Marzo 2010, 09:25 am
por bizco
Libreria en ensamblador (FASM)
ASM
farresito 2 7,579 Último mensaje 3 Agosto 2010, 18:44 pm
por farresito
KolibriOS está escrito completamente en lenguaje ensamblador usando el FASM. « 1 2 »
ASM
Weeken 11 11,428 Último mensaje 3 Diciembre 2012, 21:14 pm
por Fantasma Errante
Re: EXCEPCION, No se como resolverla, problema con EXCEL Y VB.NET[SOLUCIONADO]
.NET (C#, VB.NET, ASP)
Yaldabaot 6 4,029 Último mensaje 22 Noviembre 2013, 15:49 pm
por Yaldabaot
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines