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

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


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

Desconectado Desconectado

Mensajes: 194


Programmer


Ver Perfil WWW
[C] PEFileSize function
« en: 25 Enero 2011, 05:58 am »

Código
  1. /*
  2.    [Get size of file to base of PE]
  3.    - Programmer: The Swash
  4.    - Dedicated: Zero, Thor Psymera, Steve10120
  5. */
  6.  
  7. #include <windows.h>
  8. #include <stdio.h>
  9. #define RB "rb"
  10.  
  11. int PEFileSize(char * fPath);
  12.  
  13.  
  14. int main(void)
  15. {
  16.    printf("File size: %i", PEFileSize("C:\\test.exe"));
  17.    getchar();
  18. }
  19.  
  20. int PEFileSize(char * fPath)
  21. {
  22.    IMAGE_DOS_HEADER IDH;
  23.    IMAGE_NT_HEADERS INH;
  24.    IMAGE_SECTION_HEADER ISH;
  25.    FILE * lpFile;
  26.    int sTemp = 0, i;
  27.  
  28.    lpFile = fopen(fPath,RB);
  29.    if (lpFile != NULL)
  30.    {
  31.               fseek(lpFile, 0, SEEK_SET); // Seek to begin of file
  32.               fread(&IDH, sizeof(IDH), 1, lpFile); // Read 64 bytes to IDH struct
  33.               if (IDH.e_magic == IMAGE_DOS_SIGNATURE) // If IDH.e_magic = (MZ)
  34.               {
  35.                               fseek(lpFile, IDH.e_lfanew, SEEK_SET); // Seek in file in begin of NT Headers (PE)
  36.                               fread(&INH, sizeof(INH), 1, lpFile); // Read in structure 248 bytes
  37.                               if (INH.Signature == IMAGE_NT_SIGNATURE) // If INH.Signature = (PE)
  38.                               {
  39.                                                 for (i = 0; i < INH.FileHeader.NumberOfSections; i++) // go for all sections
  40.                                                 {
  41.                                                     fseek(lpFile, IDH.e_lfanew + sizeof(INH) + sizeof(ISH)*i, SEEK_SET); // Seek in actual section
  42.                                                     fread(&ISH, sizeof(ISH), 1, lpFile); // Read section
  43.                                                     sTemp += ISH.SizeOfRawData; // Save sizeofrawdata of section
  44.                                                 }
  45.                                                 sTemp += INH.OptionalHeader.SizeOfHeaders;
  46.                                                 fclose(lpFile);
  47.                                                 return sTemp;
  48.                               }
  49.               }
  50.               else
  51.               {
  52.                   return -1;
  53.               }
  54.    }
  55.    else
  56.    {
  57.        return -1;
  58.    }
  59. }

Que tál mis amigos, bueno estudiando el formato PE digamos que se me paso esta idea por la cabeza y no era tan dificil, lo que hace el código es obtener el tamaño original del archivo generado por el tamaño de las secciones del ejecutable + su cabecera.

Espero les sea de utilidad!


En línea

Khronos14


Desconectado Desconectado

Mensajes: 443


A lie is a lie


Ver Perfil WWW
Re: [C] PEFileSize function
« Respuesta #1 en: 25 Enero 2011, 17:53 pm »

Muy buena la función The Swash, aquí tienes la versión en Delphi:

http://foro.elhacker.net/programacion_general/delphi_pefilesize_function-t317791.0.html

Saludos.


En línea

BlackZeroX
Wiki

Desconectado Desconectado

Mensajes: 3.158


I'Love...!¡.


Ver Perfil WWW
Re: [C] PEFileSize function
« Respuesta #2 en: 26 Enero 2011, 08:51 am »

.
Viendo el codigo de The Swash re-arme el codigo de una forma mas limpia y evitando errores a toda costa, inclusive ante los archivos incompletos mas que nada, o que los imiten de alguna manera, pero no al 100%.


Código
  1.  
  2. unsigned long long GetPeSize(const char *fPath)
  3. /** Retorna el Byte donde termina TODOS los bytes de un Ejecutable en formato PE **/
  4. { /* By BlackZerox ( http://Infrangelux.sytes.net/ ) */
  5.    IMAGE_DOS_HEADER        v_idh;
  6.    IMAGE_NT_HEADERS        v_inh;
  7.    IMAGE_SECTION_HEADER    v_ish;
  8.    FILE                    *v_pFile;
  9.    unsigned long long      v_ullTemp = 0;
  10.  
  11.    if ( (v_pFile = fopen(fPath,"r")) != NULL)
  12.    {
  13.        fseek(v_pFile, 0, SEEK_SET);
  14.        if ( fread(&v_idh, 1, sizeof(IMAGE_DOS_HEADER) , v_pFile) == sizeof(IMAGE_DOS_HEADER ))/* ¿leimos lo desedo? [se evitan errores estupidos]*/
  15.            if (v_idh.e_magic == IMAGE_DOS_SIGNATURE)/* ¿Es PEFormat? */
  16.                if ( fseek(v_pFile, v_idh.e_lfanew, SEEK_SET) == 0 )/*  [se evitan errores estupidos] */
  17.                    if ( fread(&v_inh, 1 , sizeof(IMAGE_NT_HEADERS), v_pFile) == sizeof(IMAGE_NT_HEADERS) )/* ¿leimos lo desedo?  [se evitan errores estupidos] */
  18.                        if (v_inh.Signature == IMAGE_NT_SIGNATURE)/* ¿Es PEFormat? */
  19.                            if ( v_inh.FileHeader.NumberOfSections > 0 )/*  [se evitan errores estupidos] */
  20.                                v_ullTemp = v_idh.e_lfanew + sizeof(IMAGE_NT_HEADERS) + ((v_inh.FileHeader.NumberOfSections-1)*sizeof(IMAGE_SECTION_HEADER));
  21.                                if ( fseek(v_pFile, v_ullTemp , SEEK_SET) == 0 )/*  [se evitan errores estupidos] */
  22.                                    if ( sizeof(IMAGE_SECTION_HEADER) == fread(&v_ish, 1 , sizeof(IMAGE_SECTION_HEADER) , v_pFile))/* ¿leimos lo desedo?  [se evitan errores estupidos] */
  23.                                        v_ullTemp = v_ish.SizeOfRawData + v_ish.PointerToRawData;
  24.        fclose(v_pFile);
  25.    }
  26.    return v_ullTemp;
  27. }
  28.  
  29.  

O para quien no entienda aqui esta otro ( Es como a mi me gusta mas, aun que el de arriba esta mas limpio )

Código
  1.  
  2. unsigned long long GetPeSize(const char *fPath)
  3. /** Retorna el Byte donde termina TODOS los bytes de un Ejecutable en formato PE **/
  4. { /* By BlackZerox ( http://Infrangelux.sytes.net/ ) */
  5.    IMAGE_DOS_HEADER        v_idh;
  6.    IMAGE_NT_HEADERS        v_inh;
  7.    IMAGE_SECTION_HEADER    v_ish;
  8.    FILE                    *v_pFile;
  9.    unsigned long long      v_ullTemp = 0;
  10.  
  11.    if ( (v_pFile = fopen(fPath,"r")) != NULL)
  12.    {
  13.        fseek(v_pFile, 0, SEEK_SET);
  14.        if ( fread(&v_idh, 1, sizeof(IMAGE_DOS_HEADER) , v_pFile) == sizeof(IMAGE_DOS_HEADER ))
  15.        {/* ¿leimos lo desedo? [se evitan errores estupidos]*/
  16.            if (v_idh.e_magic == IMAGE_DOS_SIGNATURE)
  17.            {/* ¿Es PEFormat? */
  18.                if ( fseek(v_pFile, v_idh.e_lfanew, SEEK_SET) == 0 )
  19.                {/*  [se evitan errores estupidos] */
  20.                    if ( fread(&v_inh, 1 , sizeof(IMAGE_NT_HEADERS), v_pFile) == sizeof(IMAGE_NT_HEADERS) )
  21.                    {/* ¿leimos lo desedo?  [se evitan errores estupidos] */
  22.                        if (v_inh.Signature == IMAGE_NT_SIGNATURE)
  23.                        {/* ¿Es PEFormat? */
  24.                            if ( v_inh.FileHeader.NumberOfSections > 0 )
  25.                            {/*  [se evitan errores estupidos] */
  26.                                v_ullTemp = v_idh.e_lfanew + sizeof(IMAGE_NT_HEADERS) + ((v_inh.FileHeader.NumberOfSections-1)*sizeof(IMAGE_SECTION_HEADER));
  27.                                if ( fseek(v_pFile, v_ullTemp , SEEK_SET) == 0 )
  28.                                {/*  [se evitan errores estupidos] */
  29.                                    if ( sizeof(IMAGE_SECTION_HEADER) == fread(&v_ish, 1 , sizeof(IMAGE_SECTION_HEADER) , v_pFile))
  30.                                    {/* ¿leimos lo desedo?  [se evitan errores estupidos] */
  31.                                        v_ullTemp = v_ish.SizeOfRawData + v_ish.PointerToRawData;
  32.                                    }
  33.                                }
  34.                            }
  35.                        }
  36.                    }
  37.                }
  38.            }
  39.        }
  40.        fclose(v_pFile);
  41.    }
  42.    return v_ullTemp;
  43. }
  44.  
  45.  

P.D.: The Swash estas usando mal fread() no?...

Temibles lunas!¡.
.
« Última modificación: 26 Enero 2011, 09:02 am por BlackZeroX▓▓▒▒░░ » En línea

The Dark Shadow is my passion.
[Zero]
Wiki

Desconectado Desconectado

Mensajes: 1.082


CALL DWORD PTR DS:[0]


Ver Perfil WWW
Re: [C] PEFileSize function
« Respuesta #3 en: 26 Enero 2011, 13:45 pm »

Ambos tenéis un error que también está en todos mis códigos y que me corrigieron en un foro. No es buena idea usar sizeof(IMAGE_NT_HEADERS) para llegar a la tabla de secciones, pues el tamaño de INH no es fijo, depende del tamaño de IMAGE_OPTIONAL_HEADER y a su vez éste depende del número de directorios. También es cierto que en el 99,99% de los ejecutables el tamaño será igual al de la estructura definida en <windows.h>, pero no tiene por qué  :P.

Saludos
En línea


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

Desconectado Desconectado

Mensajes: 194


Programmer


Ver Perfil WWW
Re: [C] PEFileSize function
« Respuesta #4 en: 27 Enero 2011, 01:16 am »

Muchas gracias por la información [Zero].
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
No me va (Function)
PHP
Erik# 5 2,733 Último mensaje 20 Noviembre 2008, 20:48 pm
por Erik#
Function FileCreate [VB6]
Programación Visual Basic
The Swash 0 1,448 Último mensaje 22 Enero 2010, 17:53 pm
por The Swash
FiletoString Function [VB6]
Programación Visual Basic
The Swash 4 4,611 Último mensaje 9 Abril 2010, 06:55 am
por BlackZeroX
[Delphi] PEFileSize function
Programación General
Khronos14 1 1,962 Último mensaje 25 Enero 2011, 17:53 pm
por The Swash
API TerminateProcess function « 1 2 »
Programación C/C++
Dark Invader 12 6,488 Último mensaje 11 Octubre 2011, 05:51 am
por Karman
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines