Guest User

Untitled

a guest
Jul 22nd, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 21.36 KB | None | 0 0
  1. #include "Win32Tools.h"
  2.  
  3. static void _clean_things (HANDLE hFile, HANDLE hMapping, PBYTE pFile, const char *pErrorMessage);
  4.  
  5. DWORD
  6. get_pid_by_name (char *proc_name)
  7. {
  8.     DWORD dwPID = 0;
  9.  
  10.     PROCESSENTRY32 pe32;
  11.     HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  12.  
  13.     pe32.dwSize = sizeof(PROCESSENTRY32);
  14.  
  15.     if (hSnapshot == INVALID_HANDLE_VALUE)
  16.         return 0;
  17.  
  18.     if (!Process32First(hSnapshot, &pe32))
  19.         return 0;
  20.  
  21.     while (Process32Next(hSnapshot, &pe32))
  22.     {
  23.         if (!strcmp(proc_name, pe32.szExeFile))
  24.         {
  25.             dwPID = pe32.th32ProcessID;
  26.             break;
  27.         }
  28.     }
  29.  
  30.     CloseHandle(hSnapshot);
  31.  
  32.     return dwPID;
  33. }
  34.  
  35. int
  36. inject_dll_in_process (DWORD pid, char *dll_path)
  37. {
  38.     int pathSize;
  39.     HANDLE hProcess;
  40.     LPVOID hMemory;
  41.     LPTHREAD_START_ROUTINE hLoadLibraryA;
  42.     HANDLE hRemoteThread;
  43.     DWORD lpThreadId;
  44.  
  45.     info("Ouverture du process.");
  46.  
  47.     pathSize = strlen(dll_path) + 1;
  48.  
  49.     hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); // We open the process
  50.  
  51.     if (!hProcess)
  52.     {
  53.         warning("Le process n'a pas pu etre ouvert.");
  54.         return -1;
  55.     }
  56.  
  57.     info("Reservation et ecriture dans la memoire du processus.");
  58.  
  59.     hMemory = VirtualAllocEx(hProcess, NULL, pathSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // We allocate memory IN the process
  60.  
  61.     if(!hMemory)
  62.     {
  63.         warning("VirtualAlloc failed");
  64.         return -1;
  65.     }
  66.  
  67.     if (!WriteProcessMemory(hProcess, hMemory, dll_path, pathSize, 0)) // We write the DLL full path in the memory allocated (it will be the argument of LoadLibraryA)
  68.     {
  69.         warning("WriteProcessMemory failed");
  70.         return -1;
  71.     }
  72.  
  73.     info("Creation du thread dans le processus.");
  74.  
  75.     hLoadLibraryA = (LPTHREAD_START_ROUTINE) GetProcAddress(LoadLibrary("kernel32"), "LoadLibraryA"); // We get the address of LoadLibraryA function
  76.  
  77.     hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, hLoadLibraryA, hMemory, 0, &lpThreadId); // We execute LoadLibraryA function with the DLL full path as argument in the remote process through a new remote thread
  78.  
  79.     if (!hRemoteThread)
  80.     {
  81.         warning("CreateRemoteThread failed.");
  82.         return -1;
  83.     }
  84.  
  85.     WaitForSingleObject(hRemoteThread, INFINITE);
  86.     VirtualFreeEx(hProcess, hMemory, 0, MEM_DECOMMIT);
  87.  
  88.     CloseHandle(hProcess);
  89.     CloseHandle(hRemoteThread);
  90.  
  91.     return 0;
  92. }
  93.  
  94. HANDLE
  95. get_handle_from_pid (DWORD pid, DWORD flags)
  96. // flags = PROCESS_ALL_ACCESS generarly
  97. {
  98.     HANDLE hHandle = INVALID_HANDLE_VALUE;
  99.  
  100.     if (flags == -1)
  101.         flags = PROCESS_ALL_ACCESS;
  102.  
  103.     while (hHandle == INVALID_HANDLE_VALUE)
  104.     {
  105.         hHandle = OpenProcess (
  106.             flags,
  107.             FALSE, pid
  108.         );
  109.  
  110.         Sleep(1);
  111.     }
  112.  
  113.     return hHandle;
  114. }
  115.  
  116. void
  117. exit_process (HANDLE handle)
  118. {
  119.     DWORD code;
  120.  
  121.     GetExitCodeProcess(handle, &code);
  122.     TerminateProcess(handle, code);
  123. }
  124.  
  125. void
  126. error_exit (LPTSTR lpszFunction)
  127. {
  128.     LPTSTR  error;
  129.  
  130.     error = 0;
  131.     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  132.                   NULL, GetLastError(), 0, (LPTSTR)&error, 0, NULL);
  133.  
  134.     MessageBoxA(NULL, error, lpszFunction, MB_OK | MB_ICONWARNING);
  135.  
  136.     exit(EXIT_FAILURE);
  137. }
  138.  
  139. void
  140. enable_debug_privileges (void)
  141. {
  142.     HANDLE hProcess = GetCurrentProcess();
  143.     HANDLE hToken;
  144.     int res;
  145.  
  146.     if (OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES, &hToken))
  147.     {
  148.         res = set_privilege(hToken, SE_DEBUG_NAME, FALSE);
  149.  
  150.         if (res == 1)
  151.             info("Debug privilege granted.");
  152.         else
  153.             warning("Debug privilege ERROR.");
  154.  
  155.         CloseHandle(hToken);
  156.     }
  157. }
  158.  
  159.  
  160. MODULEENTRY32 *
  161. get_module_entry (char *process_name, DWORD pid, HWND window)
  162. {
  163.     HANDLE snapshot = CreateToolhelp32Snapshot(8u, pid);
  164.     MODULEENTRY32 *me = malloc(sizeof(MODULEENTRY32));
  165.  
  166.     me->dwSize = 0;
  167.     me->modBaseSize = 0;
  168.     me->modBaseAddr = 0;
  169.     me->hModule = NULL;
  170.  
  171.     if (snapshot == INVALID_HANDLE_VALUE)
  172.     {
  173.         warning("CreateToolhelp32Snapshot failed : GetLastError() = %d", (int) GetLastError());
  174.         return NULL;
  175.     }
  176.  
  177.     else
  178.     {
  179.         me->dwSize = sizeof(MODULEENTRY32);
  180.  
  181.         if (Module32First(snapshot, me))
  182.         {
  183.             while (strcmp(process_name, me->szModule))
  184.             {
  185.                 if (!Module32Next(snapshot, me))
  186.                 {
  187.                     warning("%s module not found !", process_name);
  188.                     CloseHandle(snapshot);
  189.                     return NULL;
  190.                 }
  191.             }
  192.  
  193.             CloseHandle(snapshot);
  194.  
  195.             return me;
  196.         }
  197.  
  198.         else
  199.         {
  200.             CloseHandle(snapshot);
  201.             warning("Module32First failed: GetLastError() = %d\n", (int) GetLastError());
  202.             return NULL;
  203.         }
  204.     }
  205. }
  206.  
  207. int
  208. set_privilege (HANDLE hToken, LPCTSTR lpszPrivilege, int bEnablePrivilege)
  209. {
  210.     LUID luid;
  211.     int bRet = FALSE;
  212.  
  213.     if (LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
  214.     {
  215.         TOKEN_PRIVILEGES tp;
  216.  
  217.         tp.PrivilegeCount = 1;
  218.         tp.Privileges[0].Luid = luid;
  219.         tp.Privileges[0].Attributes = (bEnablePrivilege) ? SE_PRIVILEGE_ENABLED : 0;
  220.  
  221.         if (AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
  222.         {
  223.             bRet = (GetLastError() == ERROR_SUCCESS);
  224.         }
  225.     }
  226.  
  227.     return bRet;
  228. }
  229.  
  230. int
  231. compare_pattern (const unsigned char *buffer, const unsigned char *pattern, const char *mask)
  232. {
  233.     for (;*mask;++mask, ++buffer, ++pattern)
  234.     {
  235.         if (*mask == 'x' && *buffer != *pattern)
  236.             return 0;
  237.     }
  238.  
  239.     return (*mask) == 0;
  240. }
  241.  
  242. DWORD
  243. find_pattern (const unsigned char *buffer, DWORD size, unsigned char *pattern, char *mask)
  244. {
  245.     for (int i = 0; i < size; i ++)
  246.     {
  247.         if (compare_pattern((buffer + i), pattern, mask))
  248.             return i;
  249.     }
  250.  
  251.     return 0;
  252. }
  253.  
  254. int
  255. read_memory_as_int (HANDLE process, DWORD address)
  256. {
  257.     unsigned char buffer[4] = {[0 ... 3] = 0};
  258.     DWORD bytes_read;
  259.  
  260.     if (!ReadProcessMemory(process, (PVOID) address, buffer, 4, &bytes_read))
  261.     {
  262.         warning("read_memory_as_int> ReadProcessMemory failed.");
  263.         return 0;
  264.     }
  265.  
  266.     return bytes_to_int32 (buffer);
  267. }
  268.  
  269. int
  270. write_memory_as_int (HANDLE process, DWORD address, unsigned int value)
  271. {
  272.     unsigned char buffer[sizeof(int)];
  273.     DWORD bytes_read;
  274.  
  275.     int32_to_bytes(value, buffer);
  276.  
  277.     if (!WriteProcessMemory(process, (PVOID) address, buffer, 4, &bytes_read))
  278.     {
  279.         warning("write_memory_as_int> WriteProcessMemory failed.");
  280.         return 0;
  281.     }
  282.  
  283.     return 1;
  284. }
  285.  
  286. int
  287. get_path_from_process (HANDLE process, char *buffer)
  288. {
  289.     if (GetModuleFileNameEx(process, NULL, buffer, MAX_PATH) == 0)
  290.     {
  291.         warning("get_full_path_from_process> GetModuleFileNameEx failed.");
  292.         return 0;
  293.     }
  294.  
  295.     return 1;
  296. }
  297.  
  298.  
  299. int
  300. bytes_to_int32 (unsigned char *bytes)
  301. {
  302.     return (((bytes[0] | (bytes[1] << 8)) | (bytes[2] << 0x10)) | (bytes[3] << 0x18));
  303. }
  304.  
  305. void
  306. int32_to_bytes (unsigned int value, unsigned char *out)
  307. {
  308.     memcpy(out, &value, sizeof(int));
  309. }
  310.  
  311. void
  312. console_set_pos (int x, int y)
  313. {
  314.     COORD coord;
  315.     coord.X = x;
  316.     coord.Y = y;
  317.  
  318.     SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
  319. }
  320.  
  321. void
  322. console_stack_pos (int todo)
  323. {
  324.     static int x, y;
  325.     CONSOLE_SCREEN_BUFFER_INFO SBInfo;
  326.  
  327.     switch (todo)
  328.     {
  329.         case PUSH_POS:
  330.             GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &SBInfo);
  331.             x = SBInfo.dwCursorPosition.X;
  332.             y = SBInfo.dwCursorPosition.Y;
  333.         break;
  334.  
  335.         case POP_POS:
  336.             console_set_pos(x, y);
  337.         break;
  338.     }
  339. }
  340.  
  341. void
  342. console_set_size (int w, int h)
  343. {
  344.     SMALL_RECT windowSize = {0, 0, w, h};
  345.     SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &windowSize);
  346. }
  347.  
  348. void
  349. console_set_col (int col)
  350. {
  351.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), col);
  352. }
  353.  
  354. void
  355. error (char *msg, ...)
  356. {
  357.     va_list args;
  358.     console_set_col(0x0C);
  359.  
  360.     printf("[!] Error : ");
  361.  
  362.     va_start (args, msg);
  363.         vfprintf (stdout, msg, args);
  364.     va_end (args);
  365.  
  366.     printf("\n");
  367.  
  368.     console_set_col(0x07);
  369.     exit(EXIT_FAILURE);
  370. }
  371.  
  372. void
  373. warning (char *msg, ...)
  374. {
  375.     va_list args;
  376.     console_set_col(0x0E);
  377.  
  378.     printf("[*] Warning : ");
  379.  
  380.     va_start (args, msg);
  381.         vfprintf (stdout, msg, args);
  382.     va_end (args);
  383.  
  384.     printf("\n");
  385.  
  386.     console_set_col(0x07);
  387. }
  388.  
  389. void
  390. info (char *msg, ...)
  391. {
  392.     va_list args;
  393.     console_set_col(0x02);
  394.  
  395.     printf("[+] Info : ");
  396.  
  397.     va_start (args, msg);
  398.         vfprintf (stdout, msg, args);
  399.     va_end (args);
  400.  
  401.     printf("\n");
  402.  
  403.     console_set_col(0x07);
  404. }
  405.  
  406. DWORD
  407. find_pattern_process (HANDLE process, DWORD start, DWORD end, unsigned char *pattern, char* mask)
  408. /*
  409. *   Exemple :
  410. *   char *pattern = "\x00\xC0\xB7\x44\x00\xC0";
  411. *   DWORD address = find_pattern_process(process, 0x800000, 0xC00000, (PBYTE) pattern, "xxx??x");
  412. */
  413. {
  414.     DWORD size = end - start;
  415.     unsigned char *buffer = malloc(size + 1);
  416.  
  417.     if (ReadProcessMemory(process, (PVOID) start, buffer, size, NULL) == FALSE)
  418.     {
  419.         warning("find_pattern_process> ReadProcessMemory failed.");
  420.         return 0;
  421.     }
  422.  
  423.     else
  424.     {
  425.         DWORD address = find_pattern(buffer, size, pattern, mask);
  426.  
  427.         if (address)
  428.             return start + address;
  429.     }
  430.  
  431.     return 0;
  432. }
  433.  
  434. int
  435. hex_to_dec (char* hex)
  436. {
  437.     int ret = 0, t = 0, n = 0;
  438.     const char *c = hex;
  439.  
  440.     while (*c && (n < 16))
  441.     {
  442.         if ((*c >= '0') && (*c <= '9'))
  443.             t = (*c - '0');
  444.  
  445.         else if ((*c >= 'A') && (*c <= 'F'))
  446.             t = (*c - 'A' + 10);
  447.  
  448.         else if((*c >= 'a') && (*c <= 'f'))
  449.             t = (*c - 'a' + 10);
  450.  
  451.         else
  452.             break;
  453.  
  454.         n++;
  455.         ret *= 16;
  456.         ret += t;
  457.         c++;
  458.  
  459.         if (n >= 8)
  460.             break;
  461.     }
  462.  
  463.     return ret;
  464. }
  465.  
  466. char *
  467. create_mask_from_file (char *filename)
  468. {
  469.     char *data = file_get_contents(filename);
  470.     int pos = 0;
  471.     int flag = 1;
  472.     int data_len = strlen(data);
  473.     int i;
  474.  
  475.     BbQueue *strArray = NULL;
  476.     BbQueue *strArray2 = NULL;
  477.     char* chArray = NULL;
  478.     char str[1024 * 100];
  479.  
  480.     while (pos <= data_len)
  481.     {
  482.         if (flag)
  483.         {
  484.             pos = str_getline(data, str, sizeof(str), pos);
  485.  
  486.             strArray = str_explode(str, " ");
  487.             chArray = str_malloc_clear(bb_queue_get_length(strArray) + 1);
  488.  
  489.             for (i = 0; i < bb_queue_get_length(strArray); i++)
  490.                 chArray[i] = 'x';
  491.  
  492.             pos = str_getline(data, str, sizeof(str), pos);
  493.  
  494.             if (pos < data_len)
  495.                 strArray2 = str_explode(str, " ");
  496.  
  497.             else
  498.                 return chArray;
  499.  
  500.             flag = 0;
  501.         }
  502.  
  503.         else
  504.         {
  505.             pos = str_getline(data, str, sizeof(str), pos);
  506.             strArray2 = str_explode(str, " ");
  507.         }
  508.  
  509.         if (bb_queue_get_length(strArray) != bb_queue_get_length(strArray2))
  510.         {
  511.             warning("create_mask_from_file > Pattern lines aren't the same length.");
  512.             return NULL;
  513.         }
  514.  
  515.         for (i = 1; i < bb_queue_get_length(strArray) + 1; i++)
  516.         {
  517.             int hex1 = hex_to_dec(bb_queue_pick_nth(strArray, i));
  518.             int hex2 = hex_to_dec(bb_queue_pick_nth(strArray2, i));
  519.  
  520.             if ((chArray[i-1] == 'x') && (hex1 != hex2))
  521.                 chArray[i-1] = '?';
  522.         }
  523.  
  524.         if (pos == -1 || pos >= data_len)
  525.         {
  526.             // End job
  527.             bb_queue_free_all(strArray, free);
  528.             bb_queue_free_all(strArray2, free);
  529.             free(data);
  530.  
  531.             return chArray;
  532.         }
  533.  
  534.         bb_queue_free_all(strArray, free);
  535.         strArray = strArray2;
  536.     }
  537.  
  538.     return chArray;
  539. }
  540.  
  541. DWORD
  542. get_module_base (char *module_name, DWORD pid)
  543. {
  544.     MODULEENTRY32 module_entry = {0};
  545.     HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
  546.  
  547.     if (!snapshot)
  548.         return 0;
  549.  
  550.     module_entry.dwSize = sizeof(module_entry);
  551.     BOOL bModule = Module32First(snapshot, &module_entry);
  552.  
  553.     while (bModule)
  554.     {
  555.         if (!strcmp(module_entry.szModule, module_name))
  556.         {
  557.             CloseHandle(snapshot);
  558.             return (DWORD) module_entry.modBaseAddr;
  559.         }
  560.  
  561.         bModule = Module32Next(snapshot, &module_entry);
  562.     }
  563.  
  564.     CloseHandle(snapshot);
  565.  
  566.     return 0;
  567. }
  568.  
  569. static void
  570. _clean_things (HANDLE hFile, HANDLE hMapping, PBYTE pFile, const char *pErrorMessage)
  571. {
  572.     if (pErrorMessage != NULL)
  573.         printf ("%s\n", pErrorMessage);
  574.  
  575.     if (hFile != NULL)
  576.         CloseHandle (hFile);
  577.  
  578.     if (pFile != NULL)
  579.         UnmapViewOfFile (pFile);
  580.  
  581.     if (hMapping != NULL)
  582.         CloseHandle (hMapping);
  583. }
  584.  
  585. PIMAGE_SECTION_HEADER
  586. GetEnclosingSectionHeader(DWORD rva, PIMAGE_NT_HEADERS pNTHeader)
  587. {
  588.     PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader);
  589.     unsigned i;
  590.  
  591.     for (i = 0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++)
  592.     {
  593.         if ((rva >= section->VirtualAddress) &&
  594.             (rva < (section->VirtualAddress + section->Misc.VirtualSize)))
  595.             return section;
  596.     }
  597.  
  598.     return 0;
  599. }
  600.  
  601.  
  602. LPVOID
  603. get_ptr_from_rva (DWORD rva, PIMAGE_NT_HEADERS pNTHeader, DWORD imageBase)
  604. {
  605.     PIMAGE_SECTION_HEADER pSectionHdr;
  606.     INT delta;
  607.  
  608.     pSectionHdr = GetEnclosingSectionHeader(rva, pNTHeader);
  609.  
  610.     if (!pSectionHdr)
  611.         return 0;
  612.  
  613.     delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData);
  614.     return (PVOID) (imageBase + rva - delta);
  615. }
  616.  
  617.  
  618. void
  619. dump_iat (char *filename)
  620. {
  621.     PIMAGE_DOS_HEADER dos_header;
  622.     LPVOID file_mapping = map_file(filename);
  623.     PIMAGE_NT_HEADERS pNTHeader;
  624.     dos_header = (PIMAGE_DOS_HEADER) file_mapping;
  625.     DWORD base = (DWORD)dos_header;
  626.  
  627.     pNTHeader = MakePtr(PIMAGE_NT_HEADERS, dos_header, dos_header->e_lfanew);
  628.  
  629.     PIMAGE_IMPORT_DESCRIPTOR importDesc;
  630.     PIMAGE_SECTION_HEADER pSection;
  631.     PIMAGE_THUNK_DATA thunk, thunkIAT=0;
  632.     PIMAGE_IMPORT_BY_NAME pOrdinalName;
  633.     DWORD importsStartRVA;
  634.     PSTR pszTimeDate;
  635.  
  636.     importsStartRVA = GetImgDirEntryRVA(pNTHeader, IMAGE_DIRECTORY_ENTRY_IMPORT);
  637.  
  638.     if (!importsStartRVA)
  639.         return;
  640.  
  641.     pSection = GetEnclosingSectionHeader(importsStartRVA, pNTHeader);
  642.  
  643.     if (!pSection)
  644.         return;
  645.  
  646.     importDesc = (PIMAGE_IMPORT_DESCRIPTOR) get_ptr_from_rva(importsStartRVA,pNTHeader,base);
  647.  
  648.     if (!importDesc)
  649.         return;
  650.  
  651.     printf("Imports Table:\n");
  652.  
  653.     while (1)
  654.     {
  655.         if ((importDesc->TimeDateStamp == 0)
  656.         &&  (importDesc->Name == 0))
  657.             break;
  658.  
  659.         printf("  %s\n", (char*) get_ptr_from_rva(importDesc->Name, pNTHeader, base) );
  660.         printf("  OrigFirstThunk:  %08X (Unbound IAT)\n", (int) importDesc->Characteristics);
  661.  
  662.         pszTimeDate = ctime((PLONG)&importDesc->TimeDateStamp);
  663.         printf("  TimeDateStamp:   %08X", (int) importDesc->TimeDateStamp );
  664.         printf( pszTimeDate ?  " -> %s" : "\n", pszTimeDate );
  665.  
  666.         printf("  ForwarderChain:  %08X\n", (int) importDesc->ForwarderChain);
  667.         printf("  First thunk RVA: %08X\n", (int) importDesc->FirstThunk);
  668.  
  669.         thunk = (PIMAGE_THUNK_DATA)importDesc->Characteristics;
  670.         thunkIAT = (PIMAGE_THUNK_DATA)importDesc->FirstThunk;
  671.  
  672.         if (thunk == 0)
  673.         {
  674.             thunk = thunkIAT;
  675.  
  676.             if (thunk == 0)
  677.                 return;
  678.         }
  679.  
  680.         // Adjust the pointer to point where the tables are in the
  681.         // mem mapped file.
  682.         thunk = (PIMAGE_THUNK_DATA) get_ptr_from_rva((DWORD)thunk, pNTHeader, base);
  683.  
  684.         if (!thunk )
  685.             return;
  686.  
  687.         thunkIAT = (PIMAGE_THUNK_DATA) get_ptr_from_rva((DWORD)thunkIAT, pNTHeader, base);
  688.  
  689.         printf("  Ordn  Name\n");
  690.  
  691.         while (1)
  692.         {
  693.             if (thunk->u1.AddressOfData == 0)
  694.                 break;
  695.  
  696.             if (thunk->u1.Ordinal & IMAGE_ORDINAL_FLAG)
  697.             {
  698.                 printf("  %4u", (int) IMAGE_ORDINAL(thunk->u1.Ordinal));
  699.             }
  700.  
  701.             else
  702.             {
  703.                 pOrdinalName = (PIMAGE_IMPORT_BY_NAME) thunk->u1.AddressOfData;
  704.                 pOrdinalName = (PIMAGE_IMPORT_BY_NAME) get_ptr_from_rva((DWORD)pOrdinalName, pNTHeader, base);
  705.  
  706.                 printf("  %4u  %s", (int) pOrdinalName->Hint, pOrdinalName->Name);
  707.             }
  708.  
  709.             // If the user explicitly asked to see the IAT entries, or
  710.             // if it looks like the image has been bound, append the address
  711.             if (importDesc->TimeDateStamp)
  712.                 printf(" (Bound to: %08X)", (int) thunkIAT->u1.Function);
  713.  
  714.             printf("\n");
  715.  
  716.             thunk++;            // Advance to next thunk
  717.             thunkIAT++;         // advance to next thunk
  718.         }
  719.  
  720.         importDesc++;   // advance to next IMAGE_IMPORT_DESCRIPTOR
  721.         printf("\n");
  722.     }
  723. }
  724.  
  725. int
  726. dump_eat (char *file_path)
  727. {
  728.     /* The IMAGE_EXPORT_DIRECTORY :
  729.     DWORD   Characteristics;
  730.     DWORD   TimeDateStamp;
  731.     WORD    MajorVersion;
  732.     WORD    MinorVersion;
  733.     DWORD   Name;                   // DLL name
  734.     DWORD   Base;                   // ordinal base
  735.     DWORD   NumberOfFunctions;      // address table entries
  736.     DWORD   NumberOfNames;          // number of name pointers
  737.     DWORD   AddressOfFunctions;     // Export address table RVA
  738.     DWORD   AddressOfNames;         // Name pointer RVA
  739.     DWORD   AddressOfNameOrdinals;  // Ordinal table RVA */
  740.  
  741.     char buffer1[500] = {0};
  742.     char buffer2[500] = {0};
  743.  
  744.     HANDLE hFile = 0, hMapping = 0;
  745.     DWORD FileSize = 0, ExportTableRVA = 0, ImageBase = 0;
  746.     PBYTE pFile = 0;
  747.     PWORD pOrdinals = 0;
  748.     PDWORD pFuncs = 0;
  749.     PIMAGE_DOS_HEADER ImageDosHeader = 0;
  750.     PIMAGE_NT_HEADERS ImageNtHeaders = 0;
  751.     PIMAGE_EXPORT_DIRECTORY ImageExportDirectory = 0;
  752.  
  753.     hFile = CreateFile(file_path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  754.  
  755.     if (hFile == INVALID_HANDLE_VALUE)
  756.     {
  757.         _clean_things (NULL, NULL, NULL, "Can't open the required DLL");
  758.         return FALSE;
  759.     }
  760.  
  761.     FileSize = GetFileSize (hFile, NULL);
  762.     if (FileSize == 0)
  763.     {
  764.         _clean_things (hFile, NULL, NULL, "FileSize is 0 !");
  765.         return FALSE;
  766.     }
  767.  
  768.     hMapping = CreateFileMapping (hFile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, NULL);
  769.     if (hMapping == NULL)
  770.     {
  771.         _clean_things (hFile, NULL, NULL, "Can't create the file mapping !");
  772.         return FALSE;
  773.     }
  774.  
  775.     pFile = (PBYTE) MapViewOfFile (hMapping, FILE_MAP_READ, 0, 0, 0);
  776.     if (pFile == NULL)
  777.     {
  778.         _clean_things (hFile, hMapping, NULL, "Can't map the requested file !");
  779.         return FALSE;
  780.     }
  781.  
  782.     ImageBase = (DWORD)pFile;
  783.     ImageDosHeader = (PIMAGE_DOS_HEADER) pFile;
  784.  
  785.     if (ImageDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
  786.     {
  787.         _clean_things (hFile, hMapping, pFile, "This file isn't a PE file !\n\n Wrong IMAGE_DOS_SIGNATURE");
  788.         return FALSE;
  789.     }
  790.  
  791.     ImageNtHeaders = (PIMAGE_NT_HEADERS)(ImageDosHeader->e_lfanew + (DWORD) ImageDosHeader);
  792.  
  793.     if (ImageNtHeaders->Signature != IMAGE_NT_SIGNATURE)
  794.     {
  795.         _clean_things (hFile, hMapping, pFile, "This file isn't a PE file !\n\n Wrong IMAGE_NT_SIGNATURE");
  796.         return FALSE;
  797.     }
  798.  
  799.     ExportTableRVA = ImageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
  800.     if (ExportTableRVA == 0)
  801.     {
  802.         _clean_things (hFile, hMapping, pFile, "Export table not found !");
  803.         return FALSE;
  804.     }
  805.  
  806.     ImageExportDirectory = (PIMAGE_EXPORT_DIRECTORY) (ExportTableRVA + ImageBase);
  807.  
  808.  
  809.     snprintf(buffer1, sizeof(buffer1), "TimeDateStamp: 0x%08lX - ", ImageExportDirectory->TimeDateStamp);
  810.     strncat(buffer1, ctime((time_t*)&ImageExportDirectory->TimeDateStamp), sizeof(buffer1));
  811.  
  812.     snprintf(buffer2, sizeof (buffer2),
  813.         "\r\nMajor Version: %i\r\n"
  814.         "Minor Version: %i\r\n"
  815.         "Name RVA: 0x%08lX - DLL Name : %s\r\n"
  816.         "Ordinal Base: 0x%08lX\r\n"
  817.         "Address Table Entries: %d\r\n"
  818.         "Number of Name Pointers: %d\r\n"
  819.         "Export Table Address RVA: 0x%08lX\r\n"
  820.         "Name Pointer RVA: 0x%08lX\r\n"
  821.         "Ordinal Table RVA: 0x%08lX",
  822.         ImageExportDirectory->MajorVersion,
  823.         ImageExportDirectory->MinorVersion,
  824.         ImageExportDirectory->Name,
  825.         (char *)ImageExportDirectory->Name + ImageBase,
  826.         ImageExportDirectory->Base,
  827.         (int) ImageExportDirectory->NumberOfFunctions,
  828.         (int) ImageExportDirectory->NumberOfNames,
  829.         ImageExportDirectory->AddressOfFunctions,
  830.         ImageExportDirectory->AddressOfNames,
  831.         ImageExportDirectory->AddressOfNameOrdinals);
  832.  
  833.     strncat (buffer1, buffer2, sizeof (buffer1));
  834.     printf("%s\n", buffer1);
  835.  
  836.     pOrdinals = (PWORD) (ImageExportDirectory->AddressOfNameOrdinals + ImageBase);
  837.     pFuncs = (PDWORD) (ImageExportDirectory->AddressOfFunctions + ImageBase);
  838.     DWORD NumOfNames = ImageExportDirectory->NumberOfNames;
  839.  
  840.     DWORD ExportTableSize = ImageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
  841.     DWORD ETUpperBoundarie = ExportTableRVA + ExportTableSize;
  842.  
  843.     for (UINT i = 0; i < ImageExportDirectory->NumberOfFunctions; i++)
  844.     {
  845.         snprintf ((LPTSTR) buffer1, sizeof (buffer1), "Ord: %04lX (0x%08lX)", ImageExportDirectory->Base + i, pFuncs[i]);
  846.  
  847.         if (pOrdinals[i] < NumOfNames)
  848.         {
  849.             PDWORD pNamePointerRVA =(PDWORD)(ImageExportDirectory->AddressOfNames + ImageBase);
  850.             PCHAR pFuncName = (PCHAR) (pNamePointerRVA[i] + (DWORD) ImageBase);
  851.             snprintf ((LPTSTR)buffer2, sizeof (buffer2), " - %s", pFuncName);
  852.             strncat (buffer1, buffer2, sizeof (buffer1));
  853.  
  854.             if ( (pFuncs[i] >= ExportTableRVA) && (pFuncs[i] <= ETUpperBoundarie) )
  855.             {
  856.                 PDWORD pFwdFunc = (PDWORD) (pFuncs[i] + (DWORD)ImageBase);
  857.                 snprintf (buffer2, sizeof (buffer2), " - Fwd to: %s", (char *)pFwdFunc);
  858.                 strncat (buffer1, buffer2, sizeof (buffer1));
  859.             }
  860.         }
  861.  
  862.         printf("%s\n", buffer1);
  863.     }
  864.  
  865.     _clean_things (hFile, hMapping, pFile, NULL);
  866.  
  867.     return TRUE;
  868. }
  869.  
  870. int
  871. is_pe (LPVOID mapping)
  872. {
  873.     PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER) mapping;
  874.  
  875.     if (dos_header->e_magic == IMAGE_DOS_SIGNATURE)
  876.     {
  877.         PIMAGE_NT_HEADERS nt_headers = (PIMAGE_NT_HEADERS) ((char*) dos_header + dos_header->e_lfanew);
  878.         return (nt_headers->Signature == IMAGE_NT_SIGNATURE);
  879.     }
  880.  
  881.     return 0;
  882. }
  883.  
  884. LPVOID
  885. map_file (char *file_path)
  886. {
  887.     LPVOID ptr_map = NULL;
  888.     HANDLE handle_file = CreateFile(file_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  889.  
  890.     if (handle_file != INVALID_HANDLE_VALUE)
  891.     {
  892.         HANDLE handle_map = CreateFileMapping(handle_file, NULL, PAGE_READONLY, 0, 0, 0);
  893.  
  894.         if (handle_map != NULL)
  895.             ptr_map = MapViewOfFile(handle_map, FILE_MAP_READ, 0, 0, 0);
  896.     }
  897.  
  898.     return ptr_map;
  899. }
Add Comment
Please, Sign In to add comment