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

 

 


Tema destacado: Trabajando con las ramas de git (tercera parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  [C]Resource Dumper.
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [C]Resource Dumper.  (Leído 3,656 veces)
The Swash

Desconectado Desconectado

Mensajes: 194


Programmer


Ver Perfil WWW
[C]Resource Dumper.
« en: 31 Mayo 2012, 21:48 pm »



Hola,

Hoy les vengo a traer una aplicación que programé y lo que en realidad hace es extraer todos los recursos de un ejecutable. Más que por su utilidad seguro pueden entender como funciona el directorio de recursos de un archivo ejecutable.
No utilizo ninguna función API de recursos proporcionada por Windows, todo está hecho a mano.

Un saludo,
Iván Portilla.

Actualizado 22 de junio de 2012, ahora soporta parámetros en su función principal y tiene corregidos errores de manejo de memoria y está mucho más optimizado.

Código
  1. /**************************************************
  2.  * Resource Dumper v0.1 .
  3.  * Programado por Iván Portilla.
  4.  * Actualizado 22 de junio de 2012
  5.  * http://www.h-sec.org & http://www.elhacker.net
  6.  **************************************************/
  7.  
  8. #include <stdio.h>
  9. #include <windows.h>
  10. #include <Strsafe.h>
  11. #define STATIC_SIZE 0x20
  12.  
  13. void GetResources(PBYTE MappedFile, DWORD ResourceRVA, PCHAR Path, PIMAGE_SECTION_HEADER ish, DWORD NumberOfSections);
  14. int RVA_TO_OFFSET(int RVA, PIMAGE_SECTION_HEADER ish, int NumberOfSections);
  15. int RESOURCE_DUMP(PCHAR lFile, PCHAR MappedName, PCHAR DumpPath);
  16. int RESOURCE_TO_FILE(PCHAR Path, PBYTE ResourceRVA, DWORD Size);
  17. PCHAR ResourceType(DWORD ResType);
  18. PCHAR UNICODE_TO_STRING(PIMAGE_RESOURCE_DIR_STRING_U String);
  19.  
  20. typedef BOOL (WINAPI * _PathIsDirectory)(PCHAR Directory);
  21. typedef BOOL (WINAPI * _PathFileExists)(PCHAR Directory);
  22.  
  23. char STR_ID[STATIC_SIZE];
  24. char STR_ID2[STATIC_SIZE];
  25. char STR_ID3[STATIC_SIZE];
  26. char STR_ID4[STATIC_SIZE];
  27. char * RESOURCES[25] = {"RT_CURSOR","RT_BITMAP","RT_ICON","RT_MENU","RT_DIALOG",
  28.                        "RT_STRING","RT_FONTDIR","RT_FONT","RT_ACCELERATOR","RT_RCDATA",
  29.                        "RT_MESSAGETABLE","RT_GROUP_CURSOR","","GROUP_ICON","","RT_VERSION",
  30.                        "RT_DLGINCLUDE","","RT_PLUGPLAY","RT_VXD","RT_ANICURSOR","RT_ANIICON",
  31.                        "RT_HTML","RT_MANIFEST","UNKNOWN"};
  32.  
  33. int main(int argc, char * argv[])
  34. {
  35.    _PathIsDirectory PathIsDirectoryA = (_PathIsDirectory)GetProcAddress(LoadLibraryA("Shlwapi.dll"), "PathIsDirectoryA");
  36.    _PathFileExists PathFileExistsA = (_PathFileExists)GetProcAddress(LoadLibraryA("Shlwapi.dll"), "PathFileExistsA");;
  37.  
  38.    printf("####  ####\n");
  39.    printf("#  #  #   #\n");
  40.    printf("# #   #    #\n");
  41.    printf("##    #    #\n");
  42.    printf("# #   #   #\n");
  43.    printf("#  #  ####\n\n");
  44.    printf("Resource Dumper Base Model v0.1\n\n");
  45.  
  46.    if ((PathFileExistsA != NULL) && (PathIsDirectoryA != NULL))
  47.    {
  48.        if (argc == 4)
  49.        {
  50.            if ((PathFileExistsA(argv[1]) == 1) && (PathIsDirectoryA(argv[3])) && (argv[2] != NULL))
  51.            {
  52.                RESOURCE_DUMP(argv[1], argv[2], argv[3]);
  53.            }
  54.            else
  55.                printf("Check your parameters [File path, File Mapped Name, Path To Save Resources] (ALL STRINGS)");
  56.        }
  57.        else
  58.            printf("This software should be execute with params [File path, File Mapped Name, Path To Save Resources] (ALL STRINGS)");
  59.    }
  60.    else
  61.        printf("Fail to load API functions of shlwapi.dll.");
  62.    getchar();
  63.    return 0;
  64. }
  65.  
  66. int RESOURCE_DUMP(PCHAR iFile, PCHAR MappedName, PCHAR DumpPath)
  67. {
  68.    HANDLE lFile, lMap;
  69.    PBYTE Mapped;
  70.    PIMAGE_DOS_HEADER IDH;
  71.    PIMAGE_NT_HEADERS INH;
  72.    DWORD Resource;
  73.  
  74.    lFile = CreateFileA(iFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,0,0);
  75.    if (lFile != INVALID_HANDLE_VALUE)
  76.    {
  77.        lMap = CreateFileMappingA(lFile, NULL, PAGE_READONLY, 0, 0, MappedName);
  78.        Mapped = (PBYTE)MapViewOfFile(lMap, FILE_MAP_READ, 0, 0, 0);
  79.        IDH = (PIMAGE_DOS_HEADER)Mapped;
  80.        if (IDH->e_magic == IMAGE_DOS_SIGNATURE)
  81.        {
  82.            INH = (PIMAGE_NT_HEADERS)&Mapped[IDH->e_lfanew];
  83.            if(INH->Signature == IMAGE_NT_SIGNATURE)
  84.            {
  85.                Resource = INH->OptionalHeader.DataDirectory[2].VirtualAddress;
  86.                if (Resource > 0)
  87.                {
  88.                    printf("Getting resources..\n");
  89.                    GetResources(Mapped, Resource, DumpPath,(PIMAGE_SECTION_HEADER)&Mapped[IDH->e_lfanew + 24 + INH->FileHeader.SizeOfOptionalHeader], INH->FileHeader.NumberOfSections);
  90.                }
  91.                else
  92.                    printf("Resource directory not present\n");
  93.            }
  94.  
  95.        }
  96.        UnmapViewOfFile(Mapped);
  97.        CloseHandle(lMap);
  98.        CloseHandle(lFile);
  99.  
  100.    }
  101.    else
  102.    {
  103.        return -1;
  104.    }
  105.  
  106.    return 0;
  107. }
  108.  
  109. void GetResources(PBYTE MappedFile, DWORD ResourceRVA, PCHAR Path, PIMAGE_SECTION_HEADER ish, DWORD NumberOfSections)
  110. {
  111.    PIMAGE_RESOURCE_DIRECTORY IRD, SUBIRD, SSUBIRD;
  112.    PIMAGE_RESOURCE_DIRECTORY_ENTRY IRDRE, SUBIRDRE, SSUBIRDRE;
  113.    PIMAGE_RESOURCE_DATA_ENTRY IRDTE;
  114.    PIMAGE_RESOURCE_DIR_STRING_U IRDS;
  115.    DWORD NumberOfEntries, NumberOfSubEntries, NumberOfSSubEntries, Counter = 0, Tick = 0, lBytes = 0;
  116.    PCHAR UNICODE_STR_PARSED = NULL;
  117.    PCHAR RES_TYPE = NULL;
  118.  
  119.    Tick = GetTickCount();
  120.    IRD = (PIMAGE_RESOURCE_DIRECTORY) &MappedFile[RVA_TO_OFFSET(ResourceRVA, ish, NumberOfSections)];
  121.    NumberOfEntries = (IRD->NumberOfNamedEntries + IRD->NumberOfIdEntries);
  122.    IRDRE = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((int)IRD + sizeof(IMAGE_RESOURCE_DIRECTORY));
  123.    printf("[Root resource directory entries: %X]\n\n", NumberOfEntries);
  124.    while(NumberOfEntries > 0)
  125.    {
  126.        if (IRDRE->DataIsDirectory == 1)
  127.        {
  128.            SecureZeroMemory(STR_ID3, STATIC_SIZE);
  129.            if (IRDRE->NameIsString == 0)
  130.            {
  131.                RES_TYPE = RESOURCES[(IRDRE->Id)-1];
  132.                printf("  [Resource type: %s]\n", RES_TYPE);
  133.                StringCchCopyA(STR_ID3, STATIC_SIZE, RES_TYPE);
  134.                StringCchCatA(STR_ID3, STATIC_SIZE, "_");
  135.            }
  136.            else
  137.            {
  138.                IRDS = (PIMAGE_RESOURCE_DIR_STRING_U) (IRDRE->NameOffset + (int)IRD);
  139.                UNICODE_STR_PARSED = UNICODE_TO_STRING(IRDS);
  140.                printf("  [Resource type: %s]\n", UNICODE_STR_PARSED);
  141.                StringCchCopyA(STR_ID3, STATIC_SIZE, UNICODE_TO_STRING(IRDS));
  142.                StringCchCatA(STR_ID3, STATIC_SIZE, "_");
  143.                GlobalFree(UNICODE_STR_PARSED);
  144.            }
  145.            SUBIRD = (PIMAGE_RESOURCE_DIRECTORY) ((int)IRD + IRDRE->OffsetToDirectory);
  146.            NumberOfSubEntries = SUBIRD->NumberOfNamedEntries + SUBIRD->NumberOfIdEntries;
  147.            SUBIRDRE = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((int)SUBIRD + sizeof(IMAGE_RESOURCE_DIRECTORY));
  148.            printf("    [Number of sub entries: %x]\n", NumberOfSubEntries);
  149.            while(NumberOfSubEntries > 0)
  150.            {
  151.                if(SUBIRDRE->DataIsDirectory == 1)
  152.                {
  153.                    printf("      [Resource Id: %i]\n", SUBIRDRE->Id);
  154.                    SSUBIRD = (PIMAGE_RESOURCE_DIRECTORY) ((int)IRD + SUBIRDRE->OffsetToDirectory);
  155.                    NumberOfSSubEntries = SSUBIRD->NumberOfNamedEntries + SSUBIRD->NumberOfIdEntries;
  156.                    SSUBIRDRE = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((int)SSUBIRD + sizeof(IMAGE_RESOURCE_DIRECTORY));
  157.                    printf("      [Number of re-sub entries: %x]\n", NumberOfSSubEntries);
  158.                    while(NumberOfSSubEntries > 0)
  159.                    {
  160.                        IRDTE = (PIMAGE_RESOURCE_DATA_ENTRY) ((int)IRD +SSUBIRDRE->OffsetToData);
  161.                        printf("        [RVA: 0x%X Size: 0x%X]\n", IRDTE->OffsetToData, IRDTE->Size);
  162.  
  163.                        SecureZeroMemory(STR_ID, STATIC_SIZE);
  164.                        SecureZeroMemory(STR_ID2, STATIC_SIZE);
  165.                        SecureZeroMemory(STR_ID4, STATIC_SIZE);
  166.  
  167.                        StringCchCatA(STR_ID4, STATIC_SIZE, STR_ID3);
  168.                        _itoa(SUBIRDRE->Id, STR_ID, 10);
  169.                        StringCchCatA(STR_ID, STATIC_SIZE, "_");
  170.                        _itoa(SSUBIRDRE->Id, STR_ID2, 10);
  171.                        StringCchCatA(STR_ID4, STATIC_SIZE, STR_ID);
  172.                        StringCchCatA(STR_ID4, STATIC_SIZE, STR_ID2);
  173.                        RESOURCE_TO_FILE(Path, (PBYTE)((int)MappedFile + RVA_TO_OFFSET(IRDTE->OffsetToData, ish, NumberOfSections)), IRDTE->Size);
  174.                        NumberOfSSubEntries = NumberOfSSubEntries - 1;
  175.                        SSUBIRDRE++;
  176.                        Counter++;
  177.                        lBytes += IRDTE->Size;
  178.                    }
  179.                }
  180.                NumberOfSubEntries = NumberOfSubEntries - 1;
  181.                SUBIRDRE++;
  182.            }
  183.        }
  184.        NumberOfEntries = NumberOfEntries - 1;
  185.        IRDRE++;
  186.    }
  187.    printf("\nResources dumped: 0x%X.", Counter);
  188.    printf("\nTime of dumped: %i miliseconds.", (GetTickCount()-Tick));
  189.    printf("\nBytes dumped: 0x%X.", lBytes);
  190. }
  191.  
  192. int RVA_TO_OFFSET(int RVA, PIMAGE_SECTION_HEADER ISH, int NumberOfSections)
  193. {
  194.    int i, Offset = 0;
  195.    if (ISH != NULL)
  196.    {
  197.        for (i = 0; i < NumberOfSections; i++)
  198.        {
  199.            if ((RVA >= (int)ISH[i].VirtualAddress) && (RVA <= (int)(ISH[i].VirtualAddress + ISH[i].Misc.VirtualSize)))
  200.            {
  201.                    Offset = (RVA - ISH[i].VirtualAddress) + ISH[i].PointerToRawData;
  202.            }
  203.        }
  204.    }
  205.    else
  206.        Offset = 0;
  207.  
  208.    return Offset;
  209. }
  210.  
  211. PCHAR UNICODE_TO_STRING(PIMAGE_RESOURCE_DIR_STRING_U String)
  212. {
  213.    PCHAR nStr = (PCHAR) GlobalAlloc(GPTR, String->Length + 1);;
  214.    WideCharToMultiByte(CP_ACP, 0, String->NameString, String->Length * 2, nStr, String->Length, NULL, NULL);
  215.    return nStr;
  216. }
  217.  
  218. int RESOURCE_TO_FILE(PCHAR Path, PBYTE ResourceRVA, DWORD Size)
  219. {
  220.    PCHAR lFile = (PCHAR)GlobalAlloc(GPTR, lstrlenA(Path) + STATIC_SIZE);
  221.    PCHAR Buffer = (PCHAR)GlobalAlloc(GPTR, Size);
  222.    HANDLE sFile;
  223.    DWORD Bytes = 0, Rest;
  224.  
  225.    CopyMemory(Buffer, ResourceRVA, Size);
  226.    StringCchCopyA(lFile, lstrlenA(Path) + STATIC_SIZE, Path);
  227.    if ((Path[lstrlenA(Path)-2] == 92) & (Path[lstrlenA(Path)-1] == 92))
  228.        StringCchCopyA(&lFile[lstrlenA(Path)], lstrlenA(Path) + STATIC_SIZE, STR_ID4);
  229.    else
  230.    {
  231.        lFile[lstrlenA(Path)+1] = 92;
  232.        lFile[lstrlenA(Path)] = 92;
  233.        StringCchCopyA(&lFile[lstrlenA(Path)+2], lstrlenA(Path) + STATIC_SIZE, STR_ID4);
  234.    }
  235.    sFile = CreateFileA(lFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, 0);
  236.    if (sFile != INVALID_HANDLE_VALUE)
  237.    {
  238.        WriteFile(sFile, Buffer, Size, &Bytes, NULL);
  239.        CloseHandle(sFile);
  240.        Rest = 0;
  241.    }
  242.    else
  243.        Rest = -1;
  244.  
  245.    GlobalFree(Buffer);
  246.    GlobalFree(lFile);
  247.    return Rest;
  248. }


« Última modificación: 22 Junio 2012, 17:26 pm por The Swash » En línea

Иōҳ


Desconectado Desconectado

Mensajes: 563


Ver Perfil
Re: [C]Resource Dumper.
« Respuesta #1 en: 31 Mayo 2012, 22:32 pm »

Gracias por compartir :D

Saludos,
Nox.


En línea

Eres adicto a la Ing. Inversa? -> www.noxsoft.net
x64core


Desconectado Desconectado

Mensajes: 1.908


Ver Perfil
Re: [C]Resource Dumper.
« Respuesta #2 en: 1 Junio 2012, 02:56 am »

gracias The Swash :) yo voy a leer de otro momento y os cuento  :)
En línea

0xDani


Desconectado Desconectado

Mensajes: 1.077



Ver Perfil
Re: [C]Resource Dumper.
« Respuesta #3 en: 1 Junio 2012, 16:09 pm »

Y por que se incluye windows.h?
En línea

I keep searching for something that I never seem to find, but maybe I won't, because I left it all behind!

I code for $$$
Hago trabajos en C/C++
Contactar por PM
The Swash

Desconectado Desconectado

Mensajes: 194


Programmer


Ver Perfil WWW
Re: [C]Resource Dumper.
« Respuesta #4 en: 1 Junio 2012, 16:29 pm »

Hola,

@daniyo, se incluye <windows.h> porque este tienes declaradas las estructuras de recursos que empleamos y el API que necesitamos para trabajar con ficheros mapeados en memoria. No te confundas, dije claramente "No utilizo API de recursos".

Un saludo,
Iván Portilla.
En línea

0xDani


Desconectado Desconectado

Mensajes: 1.077



Ver Perfil
Re: [C]Resource Dumper.
« Respuesta #5 en: 2 Junio 2012, 15:02 pm »

Ah, ok.
En línea

I keep searching for something that I never seem to find, but maybe I won't, because I left it all behind!

I code for $$$
Hago trabajos en C/C++
Contactar por PM
karmany
Colaborador
***
Desconectado Desconectado

Mensajes: 1.614


Sueñas que sueñas


Ver Perfil WWW
Re: [C]Resource Dumper.
« Respuesta #6 en: 2 Junio 2012, 21:01 pm »

Muy buen trabajo y gracias por compartir.
¡Te has metido de lleno a estudiar el PE header! Excelente.
En línea

Dryken

Desconectado Desconectado

Mensajes: 117


El arte de vencer se aprende en las derrotas


Ver Perfil WWW
Re: [C]Resource Dumper.
« Respuesta #7 en: 3 Junio 2012, 16:33 pm »

Wow!! Menudo trabajo para hacer esto, te habrá llevado mucho tiempo compañero.

Luego lo compilo a ver que tal va, aunque de primera tiene muy buena pinta  ;)
En línea

Lo intentas y fracasas, lo intentas y fracasas pero fracasas realmente cuando dejas de intentarlo.

Calc Don v0.7 - C
http://foro.elhacker.net/programacion_cc/source_calculadora_calc_don_10-t366489.0.html

Hundir la flota v0.3 - C#
http://foro.elhacker.net/net/source_c_juego_hundir_la_flota_v01-t377794.0.html
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[Source Code] - Mem Dumper 1.3 « 1 2 »
Programación Visual Basic
Mad Antrax 13 7,924 Último mensaje 29 Marzo 2007, 23:38 pm
por Mad Antrax
duda dumper « 1 2 »
Ingeniería Inversa
qwerty_crack 10 4,706 Último mensaje 20 Julio 2007, 00:20 am
por qwerty_crack
como usar el bios dumper
Juegos y Consolas
spartan 1 1,839 Último mensaje 12 Agosto 2007, 01:57 am
por spartan
Web Dumper
Dudas Generales
juancaa 7 3,934 Último mensaje 11 Noviembre 2010, 22:20 pm
por chacKos
USB Dumper y bitlocker « 1 2 »
Hacking
Adrian_Spain 11 9,015 Último mensaje 5 Octubre 2021, 23:53 pm
por Adrian_Spain
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines