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

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Seguridad Informática
| |-+  Análisis y Diseño de Malware (Moderador: fary)
| | |-+  Ejecución de Archivos desde Memoria [Base Relocation]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 [2] 3 Ir Abajo Respuesta Imprimir
Autor Tema: Ejecución de Archivos desde Memoria [Base Relocation]  (Leído 19,897 veces)
[Zero]
Wiki

Desconectado Desconectado

Mensajes: 1.082


CALL DWORD PTR DS:[0]


Ver Perfil WWW
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #10 en: 13 Diciembre 2009, 12:05 pm »

Pero estás usando el primero o el segundo ejemplo? Yo tuve problemas con el primero pero lo solucioné con RtlAdjustTokenPrivileges, dando permisos a esa zona de SeDebugPrivilege. Con el primero no tuve problema, VirtualAlloc debería de dejar bien los permisos en esa zona, prueba a llamar a VirtualProtect a ver, pero es extraño  :P.

Saludos
En línea


“El Hombre, en su orgullo, creó a Dios a su imagen y semejanza.”
Nietzsche
plaganegra

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #11 en: 13 Diciembre 2009, 18:55 pm »

use VirtualProtect y RtlAdjustTokenPrivileges pero nada.
A que te refieres con el primero o el segundo ejemplo, no se cual es cada uno  ;D
De pronto uno es el que llamaste Loader y el otro es el ExecutableRunner, el que carga el loader?
Saludos ;)
En línea

[Zero]
Wiki

Desconectado Desconectado

Mensajes: 1.082


CALL DWORD PTR DS:[0]


Ver Perfil WWW
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #12 en: 13 Diciembre 2009, 19:17 pm »

Si te fijas en el post principal hay dos apartados, un Ejecucion de Archivos con Relocation Table y otro sin ella. Por lo que dices del "Loader" supongo que te bajaste el segundo. Ese código es bastante inestable, tendrás que depurarlo bastante si quieres que funcione con todos los ejecutables. Por ejemplo falla obteniendo las apis de la IAT y al cargar la IAT, y supongo habrá algun otro fallo  :P. Lo mejor es que intentes hacer uno de 0 basándote en ese, ya que no es un código ejemplar  :xD.

Saludos  :P
En línea


“El Hombre, en su orgullo, creó a Dios a su imagen y semejanza.”
Nietzsche
SoiundTrip

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #13 en: 19 Enero 2010, 12:13 pm »

Oh,it's really cool advice)  ;D
En línea

The Swash

Desconectado Desconectado

Mensajes: 194


Programmer


Ver Perfil WWW
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #14 en: 3 Junio 2011, 00:58 am »

A mi parecer la dependencia exacta de que todas las direcciónes físicas sean realocadas da un porcentaje muy alto de fallar al cargar un ejecutable en otro espacio de memoria diferente a su ImageBase, tenía que prácticar Relocations así que decidí intentarlo en Delphi y vaya trabajo me ha dado. Gracias [Zero]
Código
  1. IMAGE_IMPORT_DESCRIPTOR = packed record
  2.    OriginalFirstThunk: DWORD;
  3.    TimeDateStamp: DWORD;
  4.    ForwarderChain: DWORD;
  5.    Name: DWORD;
  6.    FirstThunk: DWORD;
  7. end;
  8.  
  9. IMAGE_RELOCATIONS = packed record
  10.    PageRVA: DWORD;
  11.    Size:    DWORD;
  12. end;
  13.  
  14. type
  15. TArrayOfByte = array of byte;
  16. TArrayOfISH = array of TIMAGESECTIONHEADER;
  17. PIMAGEIMPORTDESCRIPTOR = ^IMAGE_IMPORT_DESCRIPTOR;
  18. PIMAGERELOCATIONS = ^IMAGE_RELOCATIONS;
  19.  
  20. function RVATOOFFSET(RVA:DWORD): DWORD;
  21. var
  22. i,n: integer;
  23. begin
  24.     for i:= 0 to IFH.NumberOfSections-1 do
  25.     begin
  26.          n:= (ish[i].VirtualAddress + ish[i].SizeOfRawData)-RVA ;
  27.          if n > 0 then
  28.          begin
  29.               Result:=(RVA - ish[i].VirtualAddress) + ish[i].PointerToRawData;
  30.               break;
  31.          end;
  32.     end;
  33.     if RVA < ish[0].VirtualAddress then Result:= RVA;
  34. end;
  35.  
  36.  
  37. procedure Execute();
  38. var
  39. IDH:         PIMAGEDOSHEADER;
  40. IOH:         PIMAGEOPTIONALHEADER;
  41. IDD:         Array[0..15] of PIMAGEDATADIRECTORY;
  42. IID:         PIMAGEIMPORTDESCRIPTOR;
  43. IR:          PIMAGERELOCATIONS;
  44. aBuffer:     TArrayOfByte;
  45. FileLen:     DWORD;
  46. hFile:       THANDLE;
  47. BytesRead:   DWORD;
  48. Signature:   PDWORD;
  49. i:           DWORD;
  50. Acumulador:  DWORD;
  51. BaseAddress: Pointer;
  52. lFunction:   PDWORD;
  53. TempAddress: DWORD;
  54. EP:          DWORD;
  55. aBlock:      DWORD;
  56. rBlock:      PWORD;
  57. dType:       DWORD;
  58. Offset:      PDWORD;
  59. Delta:       DWORD;
  60. rOffset:     DWORD;
  61. Ordinal:     DWORD;
  62. GPA:         function(hModule: Cardinal; Ordinal: Cardinal): Pointer; stdcall;
  63. begin
  64.     hFile:= CreateFileA('C:\Archivos de programa\Opera\opera.exe',GENERIC_READ, FILE_SHARE_READ,nil, OPEN_EXISTING,0,0);
  65.     If hFile <> INVALID_HANDLE_VALUE then
  66.     begin
  67.          FileLen:= GetFileSize(hFile,nil);
  68.          SetLength(aBuffer,FileLen);
  69.          ReadFile(hFile,aBuffer[0],FileLen,BytesRead,nil);
  70.     end;
  71.     GPA:= GetProcAddress(GetModuleHandle('kernel32'),'GetProcAddress');
  72.     CloseHandle(hFile);
  73.     IDH:= Pointer(aBuffer);
  74.     if IDH.e_magic = IMAGE_DOS_SIGNATURE then
  75.     begin
  76.          Signature := @aBuffer[IDH._lfanew];
  77.          if Signature^ = IMAGE_NT_SIGNATURE then
  78.          begin
  79.               IFH:= @aBuffer[IDH._lfanew + 4];
  80.               IOH:= @aBuffer[IDH._lfanew + 24];
  81.               Acumulador:= 0;
  82.               for i:=0 to 15 do
  83.               begin
  84.                    IDD[i]:= @aBuffer[IDH._lfanew + 120 + Acumulador];
  85.                    Acumulador:= Acumulador+8;
  86.               end;
  87.               SetLength(ISH, IFH.NumberOfSections-1);
  88.               Acumulador := 0;
  89.               for i:=0 to IFH.NumberOfSections-1 do
  90.               begin
  91.                    CopyMemory(@ISH[i], @aBuffer[IDH._lfanew + 248 + Acumulador], 40);
  92.                    Acumulador:= Acumulador + 40;
  93.               end;
  94.               BaseAddress:= VirtualAlloc(nil, IOH.SizeOfImage, MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  95.               CopyMemory(BaseAddress, @aBuffer[0], IOH.SizeOfHeaders);
  96.               for i:=0 to IFH.NumberOfSections-1 do
  97.               begin
  98.                    CopyMemory(Pointer(DWORD(BaseAddress)+ISH[i].VirtualAddress), @aBuffer[ISH[i].PointerToRawData], ISH[i].SizeOfRawData);
  99.               end;
  100.                              Delta:= DWORD(BaseAddress) - IOH.ImageBase;
  101.               rOffset:= RVATOOFFSET(IDD[5].VirtualAddress);
  102.               IR:= @aBuffer[rOffset];
  103.               While(IR.PageRVA <> 0) do
  104.               begin
  105.                    aBlock:= (IR.Size - 8)div 2;
  106.                    rBlock:= Pointer(DWORD(IR) + 8);
  107.                    While(aBlock > 0) do
  108.                    begin
  109.                         dType:= (rBlock^ and $F000) div $1000;
  110.                         Offset:= Pointer(DWORD(rBlock^ and $FFF) + IR.PageRVA + DWORD(BaseAddress));
  111.                         if dType = 3 then
  112.                         begin
  113.                              Offset^:= Offset^ + Delta;
  114.                         end;
  115.                         rBlock:= Pointer(DWORD(rBlock)+ 2);
  116.                         aBlock:= aBlock - 1;
  117.                    end;
  118.                    IR:= Pointer(DWORD(IR)+ IR.Size);
  119.               end;
  120.               IID:= @aBuffer[RVATOOFFSET(IDD[1].VirtualAddress)];
  121.               While(IID.Name <> 0) do
  122.               begin
  123.                    lFunction:= Pointer(DWORD(BaseAddress) + IID.FirstThunk);
  124.                    While(lFunction^ <> 0) do
  125.                    begin
  126.                         if lFunction^ > $80000000 then
  127.                         begin
  128.                              Ordinal:= lFunction^-$80000000;
  129.                              TempAddress:= DWORD(GPA(LoadLibraryA(@aBuffer[RVATOOFFSET(IID.Name)]),Ordinal));
  130.                         end else
  131.                         begin
  132.                              TempAddress:= DWORD(GetProcAddress(LoadLibraryA(@aBuffer[RVATOOFFSET(IID.Name)]),@aBuffer[RVATOOFFSET(lFunction^+2)]));
  133.                         end;
  134.                         lFunction^:= TempAddress;
  135.                         lFunction:= Pointer(DWORD(lFunction)+4);
  136.                    end;
  137.                    IID:= Pointer(DWORD(IID)+20);
  138.               end;
  139.               EP:= IOH.AddressOfEntryPoint + DWORD(BaseAddress);
  140.               asm
  141.               mov eax, EP
  142.               jmp eax;
  143.               end;
  144.          end;
  145.     end;
  146. end;

PD: Algunos errores corregidos, añadido soporte para importación por ordinales.
« Última modificación: 4 Junio 2011, 17:03 pm por The Swash » En línea

roilivethelife

Desconectado Desconectado

Mensajes: 54


Ver Perfil
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #15 en: 30 Mayo 2012, 21:08 pm »

¿Seria posible que resubieseis los links? Gracias y un saludo
En línea

[Zero]
Wiki

Desconectado Desconectado

Mensajes: 1.082


CALL DWORD PTR DS:[0]


Ver Perfil WWW
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #16 en: 31 Mayo 2012, 20:22 pm »

Que faena, no  conservo los archivos, si alguien los conserva y los pudiera resubir sería perfecto. De todas formas, con el código puedes compilarlo perfectamente, croe que no faltaba nada, incluso el ejemplo está.

Saludos
En línea


“El Hombre, en su orgullo, creó a Dios a su imagen y semejanza.”
Nietzsche
roilivethelife

Desconectado Desconectado

Mensajes: 54


Ver Perfil
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #17 en: 1 Junio 2012, 20:00 pm »

Que rabia... yo lo tuve hace tiempo en el pc pero formateé  :( :(

Intentaré compilarlo entonces, pero ¿que programa uso? Visual Studio?

salu2
En línea

[Zero]
Wiki

Desconectado Desconectado

Mensajes: 1.082


CALL DWORD PTR DS:[0]


Ver Perfil WWW
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #18 en: 3 Junio 2012, 19:40 pm »

Sí, con Visual Studio, la 2008 o la 2010 deberían de ir perfectas.

Saludos
En línea


“El Hombre, en su orgullo, creó a Dios a su imagen y semejanza.”
Nietzsche
Karman


Desconectado Desconectado

Mensajes: 673



Ver Perfil WWW
Re: Ejecución de Archivos desde Memoria [Base Relocation]
« Respuesta #19 en: 8 Junio 2012, 05:56 am »

hay dos problemas con el código, 1º que no tiene en cuenta los imports que usan ordinal en vez de nombres y el segundo son los Forwarder imports

acá tienen una versión que hice de un "full"  GetProcAddress manual:

Código
  1. FARPROC WINAPI GetProcAddress(HMODULE hModule,LPCSTR lpProcName){
  2.  DWORD index,dwExportSize,dwOrdinal=0;
  3.  if(!hModule)return NULL;
  4.  PIMAGE_DOS_HEADER pDosHeader;
  5.  PIMAGE_NT_HEADERS pNTHeader;
  6.  PIMAGE_EXPORT_DIRECTORY pExportDir;
  7. pDosHeader=(PIMAGE_DOS_HEADER)hModule;
  8. if(pDosHeader->e_magic!=IMAGE_DOS_SIGNATURE)
  9. return NULL;
  10.  pNTHeader=RVAPTR(PIMAGE_NT_HEADERS,pDosHeader,pDosHeader->e_lfanew);
  11. if(pNTHeader->Signature!=IMAGE_NT_SIGNATURE)
  12. return NULL;
  13.  pExportDir=RVAPTR(PIMAGE_EXPORT_DIRECTORY,pDosHeader,pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
  14.  dwExportSize=pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
  15.  if(!pExportDir)
  16.    return NULL;
  17.  PCHAR* pszName=RVAPTR(PCHAR*,pDosHeader,pExportDir->AddressOfNames);
  18.  PDWORD pdwAddress=RVAPTR(PDWORD,pDosHeader,pExportDir->AddressOfFunctions);
  19.  PWORD pwOrdinals=RVAPTR(PWORD,pDosHeader,pExportDir->AddressOfNameOrdinals);
  20.  if(!pszName||!pwOrdinals||!pdwAddress)
  21.    return NULL;
  22.  if(HIWORD(lpProcName)==0){
  23.    // Look up by ordinal
  24.    dwOrdinal=(LOWORD((DWORD)lpProcName)-pExportDir->Base);
  25.  }else{
  26.    // Look up by name
  27.    for(index=0;index<pExportDir->NumberOfNames;index++){
  28.      if(!lstrcmpA(RVAPTR(PCHAR,pDosHeader,pszName[index]),lpProcName)){
  29.        dwOrdinal=pwOrdinals[index];
  30.        break;
  31.      }
  32.    }
  33.  }
  34.  //Get Func Address
  35.  DWORD dwFunction=RVAPTR(DWORD,pDosHeader,pdwAddress[dwOrdinal]);
  36.  // Let's Check if is Forwarder
  37.  if((dwFunction>(ULONG_PTR)pExportDir)&&(dwFunction<((ULONG_PTR)pExportDir+dwExportSize))){
  38.    CHAR ForwarderDllName[MAX_PATH],*ForwardImportName;USHORT len;
  39.    ForwardImportName=strchr((LPSTR)dwFunction,'.');
  40.    len=ForwardImportName++-(LPSTR)dwFunction;
  41.    strncpy(ForwarderDllName,(LPSTR)dwFunction,len);
  42.    strcpy(&ForwarderDllName[len],".dll");
  43.    // Find the module associated to it (should be already loaded)
  44.    return GetProcAddress(GetModuleHandleA(ForwarderDllName),ForwardImportName);
  45.  }
  46.  return (FARPROC)dwFunction;
  47. }

capaz lo pueden adaptar...

S2
« Última modificación: 8 Junio 2012, 06:03 am por Karman » En línea

Páginas: 1 [2] 3 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
PUPE - Parcheador de archivos en ejecución y volcador de memoria
Ingeniería Inversa
ARGVC 1 3,803 Último mensaje 23 Junio 2007, 03:40 am
por tena
Modificando memoria en tiempo de ejecucion C++
Ingeniería Inversa
.CPP 5 3,536 Último mensaje 17 Septiembre 2008, 20:05 pm
por ...........
Denegar la ejecución desde el navegador
PHP
Servia 0 1,707 Último mensaje 20 Diciembre 2009, 22:01 pm
por Servia
ayuda con problema c++ relocation truncated
Programación C/C++
+ 1 Oculto(s) 7 3,895 Último mensaje 19 Mayo 2016, 01:44 am
por + 1 Oculto(s)
mover archivos con powershel desde un listado de archivos en variable de memoria
Scripting
erick_correa 1 1,702 Último mensaje 18 Septiembre 2018, 01:26 am
por EdePC
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines