Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ==++ Here's the full source code for (file 1/1) "main.cpp":: ++==
- #define STRICT
- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #include <winternl.h>
- #include <CommCtrl.h>
- #include <commdlg.h>
- #include <string>
- #include <strsafe.h>
- #include <sstream>
- #include <iomanip>
- #include <stdio.h>
- #include <vector>
- //#include "helpers.h"
- #include "resource.h"
- #pragma comment(lib, "comctl32.lib")
- namespace PEHelpers {
- std::wstring GetImageCharacteristics(DWORD characteristics) {
- if (characteristics & IMAGE_FILE_DLL) return L"(DLL)";
- if (characteristics & IMAGE_FILE_SYSTEM) return L"(DRIVER)";
- if (characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) return L"(EXE)";
- return L"(UNKNOWN)";
- }
- std::wstring GetSubsystem(WORD subsystem) {
- switch (subsystem) {
- case IMAGE_SUBSYSTEM_NATIVE: return L"(NATIVE/DRIVER)";
- case IMAGE_SUBSYSTEM_WINDOWS_GUI: return L"(GUI)";
- case IMAGE_SUBSYSTEM_WINDOWS_CUI: return L"(CONSOLE)";
- default: return L"(UNKNOWN)";
- }
- }
- std::wstring GetDataDirectoryName(int DirectoryNumber) {
- switch (DirectoryNumber) {
- case 0: return L"Export Table";
- case 1: return L"Import Table";
- case 2: return L"Resource Table";
- case 3: return L"Exception Entry";
- case 4: return L"Security Entry";
- case 5: return L"Relocation Table";
- case 6: return L"Debug Entry";
- case 7: return L"Copyright Entry";
- case 8: return L"Global PTR Entry";
- case 9: return L"TLS Entry";
- case 10: return L"Configuration Entry";
- case 11: return L"Bound Import Entry";
- case 12: return L"IAT";
- case 13: return L"Delay Import Descriptor";
- case 14: return L"COM Descriptor";
- default: return L"Unknown";
- }
- }
- std::wstring GetSectionProtection(DWORD characteristics) {
- std::wstring protection = L"(";
- bool needsSeparator = false;
- if (characteristics & IMAGE_SCN_MEM_EXECUTE) {
- protection += L"EXECUTE";
- needsSeparator = true;
- }
- if (characteristics & IMAGE_SCN_MEM_READ) {
- if (needsSeparator) protection += L" | ";
- protection += L"READ";
- needsSeparator = true;
- }
- if (characteristics & IMAGE_SCN_MEM_WRITE) {
- if (needsSeparator) protection += L" | ";
- protection += L"WRITE";
- }
- protection += L")";
- return protection;
- }
- }
- using namespace std;
- // At the top of your file, change the window class name to wide string
- #define WINDOW_CLASS_NAME L"PEAnalyzerWindow"
- //const wchar_t* const WINDOW_CLASS_NAME = L"PEAnalyzerWindow";
- // Use ANSI versions explicitly
- //#undef CreateWindow
- //#undef CreateWindowEx
- //#define CreateWindow CreateWindowW
- //#define CreateWindowEx CreateWindowExW
- // Helper function to replace printf with GUI output
- #define OUTPUT(format, ...) AppendToOutput(L##format, ##__VA_ARGS__)
- //#define OUTPUT(format, ...) AppendToOutput(format, ##__VA_ARGS__)
- //#define printf(format, ...) AppendToOutput(format, ##__VA_ARGS__)
- // Window dimensions
- #define WINDOW_WIDTH 1024
- #define WINDOW_HEIGHT 768
- #define EDIT_MARGIN 10
- // Global variables
- HWND g_hMainWindow = NULL;
- HWND g_hEditControl = NULL;
- HFONT g_hFont = NULL;
- std::wstringstream g_OutputText;
- WCHAR filePathW[MAX_PATH];
- std::vector<wchar_t> g_OutputBuffer;
- std::wstring tempBuffer; // Declare tempBuffer globally
- // Function declarations
- LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
- LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
- void CreateMainWindow(HINSTANCE hInstance);
- void InitializeControls(HWND hwnd);
- void AddMenus(HWND hwnd);
- void OpenFileDialog(HWND hwnd);
- //void AnalyzePEFile(const WCHAR* filePathW);
- void AnalyzePEFile(const wchar_t* filePathW);
- HANDLE GetFileContent(const wchar_t* lpFilePath);
- /*void GetDataDirectories(PIMAGE_DATA_DIRECTORY pImageDataDirectory);
- PIMAGE_SECTION_HEADER GetSections(const PIMAGE_SECTION_HEADER pImageSectionHeader,
- int NumberOfSections, DWORD dImportAddress);
- void GetImports32(PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor,
- DWORD dRawOffset, const PIMAGE_SECTION_HEADER pImageImportSection);
- void GetImports64(PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor,
- DWORD dRawOffset, const PIMAGE_SECTION_HEADER pImageImportSection);*/
- void AppendToOutput(const wchar_t* format, ...);
- void UpdateEditControl();
- // Main window class name
- //const char* const WINDOW_CLASS_NAME = "PEAnalyzerWindow";
- int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
- INITCOMMONCONTROLSEX icc = { sizeof(INITCOMMONCONTROLSEX), ICC_WIN95_CLASSES };
- InitCommonControlsEx(&icc);
- CreateMainWindow(hInstance);
- if (!g_hMainWindow) return -1;
- ShowWindow(g_hMainWindow, nCmdShow);
- UpdateWindow(g_hMainWindow);
- MSG msg = {};
- while (GetMessage(&msg, NULL, 0, 0)) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- if (g_hFont) DeleteObject(g_hFont);
- return (int)msg.wParam;
- }
- void CreateMainWindow(HINSTANCE hInstance) {
- WNDCLASSEXW wc = { sizeof(WNDCLASSEXW), 0, WindowProc, 0, 0, hInstance, LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)), LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_WINDOW + 1), NULL, WINDOW_CLASS_NAME, LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)) };
- RegisterClassExW(&wc);
- // Get screen dimensions
- int screenWidth = GetSystemMetrics(SM_CXSCREEN);
- int screenHeight = GetSystemMetrics(SM_CYSCREEN);
- // Calculate center position
- int windowX = (screenWidth - WINDOW_WIDTH) / 2;
- int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
- // Remove WS_MAXIMIZEBOX and WS_THICKFRAME from the window style
- DWORD style = (WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX) & ~WS_THICKFRAME;
- //WS_OVERLAPPEDWINDOW ~~> style
- g_hMainWindow = CreateWindowExW(0, WINDOW_CLASS_NAME, L"PE File Analyzer", style, windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT, nullptr, nullptr, hInstance, nullptr);
- }
- void InitializeControls(HWND hwnd) {
- g_hEditControl = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
- WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL,
- EDIT_MARGIN, EDIT_MARGIN,
- WINDOW_WIDTH - (2 * EDIT_MARGIN), WINDOW_HEIGHT - (2 * EDIT_MARGIN),
- hwnd, nullptr,
- (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), nullptr);
- g_hFont = CreateFont(-14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0,
- ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
- DEFAULT_QUALITY, DEFAULT_PITCH | FF_MODERN, L"Consolas");
- if (g_hFont)
- SendMessage(g_hEditControl, WM_SETFONT, (WPARAM)g_hFont, TRUE);
- // Add this line to subclass the Edit control
- SetWindowSubclass(g_hEditControl, EditSubclassProc, 0, 0);
- }
- void AddMenus(HWND hwnd) {
- HMENU hMenuBar = CreateMenu();
- HMENU hFileMenu = CreateMenu();
- AppendMenu(hMenuBar, MF_POPUP, (UINT_PTR)hFileMenu, L"&File");
- AppendMenu(hFileMenu, MF_STRING, 1, L"&Open");
- AppendMenu(hFileMenu, MF_STRING, 2, L"E&xit");
- SetMenu(hwnd, hMenuBar);
- }
- LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) {
- if (uMsg == WM_KEYDOWN) {
- switch (wParam) {
- case VK_F1: // F1 key
- SendMessage(GetParent(hwnd), WM_KEYDOWN, VK_F1, 0);
- return 0;
- case VK_ESCAPE: // Escape key
- SendMessage(GetParent(hwnd), WM_KEYDOWN, VK_ESCAPE, 0);
- return 0;
- }
- }
- return DefSubclassProc(hwnd, uMsg, wParam, lParam);
- }
- LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
- switch (uMsg) {
- case WM_CREATE: InitializeControls(hwnd); AddMenus(hwnd); return 0;
- case WM_SIZE: SetWindowPos(g_hEditControl, NULL, EDIT_MARGIN, EDIT_MARGIN, LOWORD(lParam) - (2 * EDIT_MARGIN), HIWORD(lParam) - (2 * EDIT_MARGIN), SWP_NOZORDER); return 0;
- case WM_KEYDOWN:
- switch (wParam) {
- case VK_F1:
- MessageBoxW(hwnd,
- L"PE Header Parser 2.3 GUI-based Programmed in C++ Win32 API (1173 lines of code) by Entisoft Software(c) Evans Thorpemorton",
- L"About",
- MB_OK | MB_ICONINFORMATION);
- return 0;
- case VK_ESCAPE:
- PostQuitMessage(0);
- return 0;
- }
- break;
- case WM_COMMAND: if (LOWORD(wParam) == 1) OpenFileDialog(hwnd); if (LOWORD(wParam) == 2) PostQuitMessage(0); return 0;
- case WM_DESTROY: PostQuitMessage(0); return 0;
- }
- return DefWindowProc(hwnd, uMsg, wParam, lParam);
- }
- void OpenFileDialog(HWND hwnd) {
- WCHAR fileName[MAX_PATH] = L"";
- OPENFILENAMEW ofn = { sizeof(OPENFILENAMEW), hwnd, NULL, L"Executable Files (*.exe;*.dll)\0*.exe;*.dll\0All Files (*.*)\0*.*\0", NULL, 0, 1, fileName, MAX_PATH, NULL, 0, NULL, NULL, OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, 0, 0, L"exe", NULL, NULL, NULL };
- if (GetOpenFileNameW(&ofn)) {
- SetWindowTextW(g_hEditControl, L"");
- g_OutputText.str(L"");
- g_OutputText.clear();
- AnalyzePEFile(ofn.lpstrFile);
- UpdateEditControl();
- }
- }
- class FileMapper {
- private:
- HANDLE hFile = INVALID_HANDLE_VALUE;
- HANDLE hMapping = nullptr;
- LPVOID lpView = nullptr;
- public:
- ~FileMapper() {
- if (lpView) UnmapViewOfFile(lpView);
- if (hMapping) CloseHandle(hMapping);
- if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);
- }
- bool Initialize(const wchar_t* path) {
- hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
- if (hFile == INVALID_HANDLE_VALUE) return false;
- hMapping = CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 0, nullptr);
- if (!hMapping) return false;
- lpView = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
- return lpView != nullptr;
- }
- LPVOID GetView() const { return lpView; }
- };
- // Modified AppendToOutput to handle newlines properly:
- void AppendToOutput(const wchar_t* format, ...) {
- std::vector<wchar_t> buffer(1024);
- va_list args;
- va_start(args, format);
- while (true) {
- int result = _vsnwprintf(buffer.data(), buffer.size(), format, args);
- if (result >= 0) break;
- buffer.resize(buffer.size() * 2);
- }
- va_end(args);
- // Convert \n to \r\n
- std::wstring output = buffer.data();
- size_t pos = 0;
- while ((pos = output.find(L'\n', pos)) != std::wstring::npos) {
- if (pos == 0 || output[pos - 1] != L'\r') {
- output.insert(pos, L"\r");
- pos += 2;
- }
- else {
- pos++;
- }
- }
- g_OutputText << output;
- UpdateEditControl();
- }
- /*
- void AppendToOutput(const wchar_t* format, ...) {
- wchar_t buffer[16384]; // Ensure sufficient buffer size
- va_list args;
- va_start(args, format);
- StringCchVPrintfW(buffer, ARRAYSIZE(buffer), format, args);
- va_end(args);
- tempBuffer += buffer;
- // Update Edit Control periodically to improve performance
- if (tempBuffer.size() > 8000) {
- g_OutputText << tempBuffer;
- tempBuffer.clear();
- SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
- SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
- SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
- }
- }
- // Final update to flush any remaining content
- void FlushOutput() {
- if (!tempBuffer.empty()) {
- g_OutputText << tempBuffer;
- tempBuffer.clear();
- SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
- SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
- SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
- }
- }
- */
- /*
- //use below ^^ ALWAYS
- void AppendToOutput(const wchar_t* format, ...) {
- va_list args;
- va_start(args, format);
- // Use a vector as a dynamically resizable buffer
- std::vector<wchar_t> buffer(16384); // Start with an initial size
- int result = -1;
- while (true) {
- // Attempt to format the string
- result = _vsnwprintf(buffer.data(), buffer.size(), format, args);
- if (result >= 0 && static_cast<size_t>(result) < buffer.size()) {
- // Successfully formatted within the current buffer size
- break;
- }
- // Resize the buffer and try again
- buffer.resize(buffer.size() * 2);
- }
- va_end(args);
- // Convert `\n` to `\r\n` for proper display in the EditBox
- std::wstring formattedOutput(buffer.data());
- size_t pos = 0;
- while ((pos = formattedOutput.find(L'\n', pos)) != std::wstring::npos) {
- formattedOutput.replace(pos, 1, L"\r\n");
- pos += 2; // Move past the replacement
- }
- // Append to the global output buffer
- g_OutputText << formattedOutput;
- // Update the EditBox periodically to prevent overloading
- if (g_OutputText.str().size() > 8000) {
- SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
- SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
- SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
- }
- }
- //use above ^^ ALWAYS
- */
- //currentlatest
- /*void AppendToOutput(const wchar_t* format, ...) {
- wchar_t buffer[4096];
- va_list args;
- va_start(args, format);
- StringCchVPrintfW(buffer, ARRAYSIZE(buffer), format, args);
- va_end(args);
- g_OutputText << buffer;
- SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
- SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
- SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
- }
- */
- //use-below-basic-failsafe-working vv
- //basic test function
- /*void AnalyzePEFile(const wchar_t* filePathW) {
- OUTPUT("[+] Analyzing file: %s\n", filePathW);
- LPVOID lpFileContent = GetFileContent(filePathW);
- if (!lpFileContent) { OUTPUT("[-] Could not read file.\n"); return; }
- PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileContent;
- if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) { OUTPUT("[-] Invalid DOS signature.\n"); HeapFree(GetProcessHeap(), 0, lpFileContent); return; }
- PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)((DWORD_PTR)lpFileContent + dosHeader->e_lfanew);
- if (ntHeaders->Signature != IMAGE_NT_SIGNATURE) { OUTPUT("[-] Invalid NT signature.\n"); HeapFree(GetProcessHeap(), 0, lpFileContent); return; }
- OUTPUT("[+] PE file analyzed successfully.\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- UpdateEditControl();
- }*/
- //use-above-basic-failsafe-working vv
- //use vectors for unlimited size growth of buffer, use an alternative to editbox, check for fast loops overloading, in its primitive form it works properly! try w/o getimports3264 datadirectories getsections
- void AnalyzePEFile(const wchar_t* filePathW) {
- OUTPUT("[+] Starting PE Analysis for: %s\n\n", filePathW);
- FileMapper mapper;
- if (!mapper.Initialize(filePathW)) {
- OUTPUT("[-] Failed to open file! Error: %d\r\n", GetLastError());
- return;
- }
- // Open and read file
- HANDLE hFile = CreateFileW(filePathW, GENERIC_READ, FILE_SHARE_READ, nullptr,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
- if (hFile == INVALID_HANDLE_VALUE) {
- OUTPUT("[-] Failed to open file! Error: %d\n", GetLastError());
- return;
- }
- DWORD fileSize = GetFileSize(hFile, nullptr);
- if (fileSize == INVALID_FILE_SIZE) {
- CloseHandle(hFile);
- OUTPUT("[-] Failed to get file size! Error: %d\n", GetLastError());
- return;
- }
- HANDLE hFileMapping = CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 0, nullptr);
- if (!hFileMapping) {
- CloseHandle(hFile);
- OUTPUT("[-] Failed to create file mapping! Error: %d\n", GetLastError());
- return;
- }
- LPVOID lpFileContent = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
- if (!lpFileContent) {
- CloseHandle(hFileMapping);
- CloseHandle(hFile);
- OUTPUT("[-] Failed to map view of file! Error: %d\n", GetLastError());
- return;
- }
- const auto pImageDosHeader = static_cast<PIMAGE_DOS_HEADER>(mapper.GetView());
- if (pImageDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
- OUTPUT("[-] Invalid DOS signature!\r\n");
- return;
- }
- const auto pImageNtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(
- static_cast<BYTE*>(mapper.GetView()) + pImageDosHeader->e_lfanew);
- if (pImageNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
- OUTPUT("[-] Invalid NT signature!\r\n");
- return;
- }
- // Print File Header Information
- OUTPUT("[+] PE FILE HEADER\n");
- OUTPUT("\tMachine: 0x%X\n", pImageNtHeaders->FileHeader.Machine);
- OUTPUT("\tNumberOfSections: 0x%X\n", pImageNtHeaders->FileHeader.NumberOfSections);
- OUTPUT("\tTimeDateStamp: 0x%X\n", pImageNtHeaders->FileHeader.TimeDateStamp);
- OUTPUT("\tPointerToSymbolTable: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->FileHeader.PointerToSymbolTable));
- OUTPUT("\tNumberOfSymbols: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->FileHeader.NumberOfSymbols));
- OUTPUT("\tSizeOfOptionalHeader: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->FileHeader.SizeOfOptionalHeader));
- OUTPUT("\tCharacteristics: 0x%X %s\n\n",
- pImageNtHeaders->FileHeader.Characteristics,
- PEHelpers::GetImageCharacteristics(pImageNtHeaders->FileHeader.Characteristics).c_str());
- // Print Optional Header Information
- OUTPUT("[+] PE OPTIONAL HEADER\n");
- OUTPUT("\tMagic: 0x%X\n", pImageNtHeaders->OptionalHeader.Magic);
- OUTPUT("\tAddressOfEntryPoint: 0x%X\n", pImageNtHeaders->OptionalHeader.AddressOfEntryPoint);
- OUTPUT("\tImageBase: 0x%llX\n", (ULONGLONG)pImageNtHeaders->OptionalHeader.ImageBase);
- OUTPUT("\tSectionAlignment: 0x%X\n", pImageNtHeaders->OptionalHeader.SectionAlignment);
- OUTPUT("\tFileAlignment: 0x%X\n", pImageNtHeaders->OptionalHeader.FileAlignment);
- // Added missing Optional Header fields
- OUTPUT("\tMajorOperatingSystemVersion: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.MajorOperatingSystemVersion));
- OUTPUT("\tMinorOperatingSystemVersion: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.MinorOperatingSystemVersion));
- OUTPUT("\tMajorImageVersion: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.MajorImageVersion));
- OUTPUT("\tMinorImageVersion: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.MinorImageVersion));
- OUTPUT("\tMajorSubsystemVersion: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.MajorSubsystemVersion));
- OUTPUT("\tMinorSubsystemVersion: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.MinorSubsystemVersion));
- OUTPUT("\tWin32VersionValue: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.Win32VersionValue));
- OUTPUT("\tSizeOfImage: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.SizeOfImage));
- OUTPUT("\tSizeOfHeaders: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.SizeOfHeaders));
- OUTPUT("\tCheckSum: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.CheckSum));
- OUTPUT("\tSubsystem: 0x%X %s\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.Subsystem),
- PEHelpers::GetSubsystem(pImageNtHeaders->OptionalHeader.Subsystem).c_str());
- OUTPUT("\tDllCharacteristics: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.DllCharacteristics));
- OUTPUT("\tSizeOfStackReserve: 0x%llX\r\n",
- static_cast<ULONGLONG>(pImageNtHeaders->OptionalHeader.SizeOfStackReserve));
- OUTPUT("\tSizeOfStackCommit: 0x%llX\r\n",
- static_cast<ULONGLONG>(pImageNtHeaders->OptionalHeader.SizeOfStackCommit));
- OUTPUT("\tSizeOfHeapReserve: 0x%llX\r\n",
- static_cast<ULONGLONG>(pImageNtHeaders->OptionalHeader.SizeOfHeapReserve));
- OUTPUT("\tSizeOfHeapCommit: 0x%llX\r\n",
- static_cast<ULONGLONG>(pImageNtHeaders->OptionalHeader.SizeOfHeapCommit));
- OUTPUT("\tLoaderFlags: 0x%X\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.LoaderFlags));
- OUTPUT("\tNumberOfRvaAndSizes: 0x%X\r\n\r\n",
- static_cast<DWORD>(pImageNtHeaders->OptionalHeader.NumberOfRvaAndSizes));
- OUTPUT("\tSubsystem: 0x%X %s\n\n",
- pImageNtHeaders->OptionalHeader.Subsystem,
- PEHelpers::GetSubsystem(pImageNtHeaders->OptionalHeader.Subsystem).c_str());
- // Print Data Directories
- OUTPUT("[+] PE DATA DIRECTORIES\n");
- for (int i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++) {
- const auto& dir = pImageNtHeaders->OptionalHeader.DataDirectory[i];
- if (dir.VirtualAddress != 0) {
- OUTPUT("\t%s:\n", PEHelpers::GetDataDirectoryName(i).c_str());
- OUTPUT("\t\tVirtualAddress: 0x%X\n", dir.VirtualAddress);
- OUTPUT("\t\tSize: 0x%X\n", dir.Size);
- }
- }
- // Analyze Sections
- OUTPUT("\n[+] PE IMAGE SECTIONS\r\n");
- auto pSection = IMAGE_FIRST_SECTION(pImageNtHeaders);
- for (WORD i = 0; i < pImageNtHeaders->FileHeader.NumberOfSections; i++, pSection++) {
- // Create a null-terminated string from the section name
- char sectionName[IMAGE_SIZEOF_SHORT_NAME + 1] = {};
- memcpy(sectionName, pSection->Name, IMAGE_SIZEOF_SHORT_NAME);
- // Remove any non-printable characters
- for (int j = 0; j < IMAGE_SIZEOF_SHORT_NAME; j++) {
- if (!isprint(static_cast<unsigned char>(sectionName[j]))) {
- sectionName[j] = '\0';
- }
- }
- // Convert to wide string
- wchar_t wideSectionName[IMAGE_SIZEOF_SHORT_NAME + 1] = {};
- MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED,
- sectionName, -1,
- wideSectionName, IMAGE_SIZEOF_SHORT_NAME + 1);
- OUTPUT("\tSECTION : %s\r\n", wideSectionName);
- OUTPUT("\t\tMisc (PhysicalAddress) : 0x%X\r\n", pSection->Misc.PhysicalAddress);
- OUTPUT("\t\tMisc (VirtualSize) : 0x%X\r\n", pSection->Misc.VirtualSize);
- OUTPUT("\t\tVirtualAddress : 0x%X\r\n", pSection->VirtualAddress);
- OUTPUT("\t\tSizeOfRawData : 0x%X\r\n", pSection->SizeOfRawData);
- OUTPUT("\t\tPointerToRawData : 0x%X\r\n", pSection->PointerToRawData);
- OUTPUT("\t\tPointerToRelocations : 0x%X\r\n", pSection->PointerToRelocations);
- OUTPUT("\t\tPointerToLinenumbers : 0x%X\r\n", pSection->PointerToLinenumbers);
- OUTPUT("\t\tNumberOfRelocations : 0x%X\r\n", pSection->NumberOfRelocations);
- OUTPUT("\t\tNumberOfLinenumbers : 0x%X\r\n", pSection->NumberOfLinenumbers);
- OUTPUT("\t\tCharacteristics : 0x%X %s\r\n\r\n",
- pSection->Characteristics,
- PEHelpers::GetSectionProtection(pSection->Characteristics).c_str());
- }
- // Analyze Imports
- const auto& importDir = pImageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
- if (importDir.VirtualAddress && importDir.Size) {
- OUTPUT("\n[+] IMPORTED DLLS AND FUNCTIONS\r\n");
- // Find the section containing imports
- auto pSection = IMAGE_FIRST_SECTION(pImageNtHeaders);
- PIMAGE_SECTION_HEADER pImportSection = nullptr;
- // Find the import section
- for (WORD i = 0; i < pImageNtHeaders->FileHeader.NumberOfSections; i++, pSection++) {
- if (importDir.VirtualAddress >= pSection->VirtualAddress &&
- importDir.VirtualAddress < (pSection->VirtualAddress + pSection->Misc.VirtualSize)) {
- pImportSection = pSection;
- break;
- }
- }
- if (!pImportSection) {
- OUTPUT("[-] Could not find import section\r\n");
- return;
- }
- // Get the import descriptor
- auto pImportDesc = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(
- (BYTE*)lpFileContent +
- pImportSection->PointerToRawData +
- (importDir.VirtualAddress - pImportSection->VirtualAddress));
- // Process all DLLs
- while (pImportDesc && pImportDesc->Name != 0) {
- // Get DLL name
- const char* dllName = reinterpret_cast<const char*>(
- (BYTE*)lpFileContent +
- pImportSection->PointerToRawData +
- (pImportDesc->Name - pImportSection->VirtualAddress));
- if (!IsBadReadPtr(dllName, 1)) {
- std::vector<wchar_t> wideDllName(MAX_PATH);
- MultiByteToWideChar(CP_ACP, 0, dllName, -1,
- wideDllName.data(), MAX_PATH);
- // Print DLL information
- OUTPUT("\n\tDLL NAME : %s\r\n", wideDllName.data());
- OUTPUT("\tCharacteristics : 0x%X\r\n", pImportDesc->Characteristics);
- OUTPUT("\tOriginalFirstThunk : 0x%X\r\n", pImportDesc->OriginalFirstThunk);
- OUTPUT("\tTimeDateStamp : 0x%X\r\n", pImportDesc->TimeDateStamp);
- OUTPUT("\tForwarderChain : 0x%X\r\n", pImportDesc->ForwarderChain);
- OUTPUT("\tFirstThunk : 0x%X\r\n", pImportDesc->FirstThunk);
- OUTPUT("\n\tImported Functions :\r\n\r\n");
- // Process functions using OriginalFirstThunk
- if (pImportDesc->OriginalFirstThunk) {
- auto pThunk = reinterpret_cast<PIMAGE_THUNK_DATA>(
- (BYTE*)lpFileContent +
- pImportSection->PointerToRawData +
- (pImportDesc->OriginalFirstThunk - pImportSection->VirtualAddress));
- // Process all functions for this DLL
- while (pThunk && pThunk->u1.AddressOfData) {
- if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG)) {
- auto pImportByName = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(
- (BYTE*)lpFileContent +
- pImportSection->PointerToRawData +
- (pThunk->u1.AddressOfData - pImportSection->VirtualAddress));
- if (!IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
- std::vector<wchar_t> wideFuncName(MAX_PATH);
- MultiByteToWideChar(CP_ACP, 0,
- reinterpret_cast<const char*>(pImportByName->Name),
- -1, wideFuncName.data(), MAX_PATH);
- OUTPUT("\t\t%s\r\n", wideFuncName.data());
- }
- }
- pThunk++;
- }
- }
- }
- pImportDesc++;
- }
- }
- cleanup:
- if (lpFileContent) {
- UnmapViewOfFile(lpFileContent);
- }
- if (hFileMapping) {
- CloseHandle(hFileMapping);
- }
- if (hFile) {
- CloseHandle(hFile);
- }
- UpdateEditControl();
- }
- /*
- //use below vv ALWAYS
- void AnalyzePEFile(const wchar_t* filePathW) {
- OUTPUT("[+] Starting PE Analysis for: %s\n\n", filePathW);
- LPVOID lpFileContent = GetFileContent(filePathW);
- if (!lpFileContent) {
- OUTPUT("[-] Failed to read file content!\n");
- return;
- }
- const auto pImageDosHeader = static_cast<PIMAGE_DOS_HEADER>(lpFileContent);
- if (pImageDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
- OUTPUT("[-] Invalid DOS signature!\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- return;
- }
- const auto pImageNtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>((DWORD_PTR)lpFileContent + pImageDosHeader->e_lfanew);
- if (pImageNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
- OUTPUT("[-] Invalid NT signature!\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- return;
- }
- //UpdateEditControl(); //added just now remove line!
- OUTPUT("[+] PE FILE HEADER\n");
- OUTPUT("\tMachine : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.Machine);
- OUTPUT("\tNumberOfSections : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.NumberOfSections);
- OUTPUT("\tTimeDateStamp : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.TimeDateStamp);
- OUTPUT("\tPointerToSymbolTable : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.PointerToSymbolTable);
- OUTPUT("\tNumberOfSymbols : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.NumberOfSymbols);
- OUTPUT("\tSizeOfOptionalHeader : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.SizeOfOptionalHeader);
- OUTPUT("\tCharacteristics : 0x%X %s\n\n", (uintptr_t)pImageNtHeaders->FileHeader.Characteristics, GetImageCharacteristics(pImageNtHeaders->FileHeader.Characteristics));
- OUTPUT("[+] PE OPTIONAL HEADER\n");
- OUTPUT("\tMagic : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.Magic);
- OUTPUT("\tAddressOfEntryPoint : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.AddressOfEntryPoint);
- OUTPUT("\tImageBase : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.ImageBase);
- OUTPUT("\tSectionAlignment : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SectionAlignment);
- OUTPUT("\tFileAlignment : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.FileAlignment);
- OUTPUT("\tMajorOperatingSystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MajorOperatingSystemVersion);
- OUTPUT("\tMinorOperatingSystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MinorOperatingSystemVersion);
- OUTPUT("\tMajorImageVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MajorImageVersion);
- OUTPUT("\tMinorImageVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MinorImageVersion);
- OUTPUT("\tMajorSubsystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MajorSubsystemVersion);
- OUTPUT("\tMinorSubsystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MinorSubsystemVersion);
- OUTPUT("\tWin32VersionValue : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.Win32VersionValue);
- OUTPUT("\tSizeOfImage : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfImage);
- OUTPUT("\tSizeOfHeaders : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfHeaders);
- OUTPUT("\tCheckSum : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.CheckSum);
- OUTPUT("\tSubsystem : 0x%X %s\n", (uintptr_t)pImageNtHeaders->OptionalHeader.Subsystem, GetSubsystem(pImageNtHeaders->OptionalHeader.Subsystem));
- OUTPUT("\tDllCharacteristics : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.DllCharacteristics);
- OUTPUT("\tSizeOfStackReserve : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfStackReserve);
- OUTPUT("\tSizeOfStackCommit : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfStackCommit);
- OUTPUT("\tSizeOfHeapReserve : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfHeapReserve);
- OUTPUT("\tSizeOfHeapCommit : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfHeapCommit);
- OUTPUT("\tLoaderFlags : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.LoaderFlags);
- OUTPUT("\tNumberOfRvaAndSizes : 0x%X\n\n", (uintptr_t)pImageNtHeaders->OptionalHeader.NumberOfRvaAndSizes);
- //UpdateEditControl(); //added just now remove line!
- GetDataDirectories(&pImageNtHeaders->OptionalHeader.DataDirectory[0]);
- const auto pImageSectionHeader = reinterpret_cast<PIMAGE_SECTION_HEADER>((DWORD_PTR)pImageNtHeaders + sizeof(IMAGE_NT_HEADERS));
- const auto pImageImportSection = GetSections(pImageSectionHeader, pImageNtHeaders->FileHeader.NumberOfSections, pImageNtHeaders->OptionalHeader.DataDirectory[1].VirtualAddress);
- if (!pImageImportSection) {
- OUTPUT("[-] Error: Could not find import section!\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- return;
- }
- const auto pImageImportDescriptor = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>((DWORD_PTR)lpFileContent + pImageImportSection->PointerToRawData);
- if (pImageNtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_I386) {
- GetImports32(pImageImportDescriptor, (DWORD)lpFileContent + pImageImportSection->PointerToRawData, pImageImportSection);
- }
- else if (pImageNtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) {
- GetImports64(pImageImportDescriptor, (DWORD)lpFileContent + pImageImportSection->PointerToRawData, pImageImportSection);
- }
- else {
- OUTPUT("[-] Unsupported architecture!\n");
- }
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- UpdateEditControl();
- }
- void GetDataDirectories(PIMAGE_DATA_DIRECTORY pImageDataDirectory) {
- OUTPUT("[+] PE DATA DIRECTORIES\n");
- for (int i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; ++i, ++pImageDataDirectory) {
- if (pImageDataDirectory->VirtualAddress == 0) continue;
- OUTPUT("\tDataDirectory (%s) VirtualAddress : 0x%X\n", GetDataDirectoryName(i), (uintptr_t)pImageDataDirectory->VirtualAddress);
- OUTPUT("\tDataDirectory (%s) Size : 0x%X\n\n", GetDataDirectoryName(i), (uintptr_t)pImageDataDirectory->Size);
- }
- }
- PIMAGE_SECTION_HEADER GetSections(const PIMAGE_SECTION_HEADER pImageSectionHeader, int NumberOfSections, DWORD dImportAddress) {
- PIMAGE_SECTION_HEADER pImageImportHeader = nullptr;
- OUTPUT("\n[+] PE IMAGE SECTIONS\n");
- for (int i = 0; i < NumberOfSections; ++i) {
- const auto pCurrentSectionHeader = reinterpret_cast<PIMAGE_SECTION_HEADER>((DWORD_PTR)pImageSectionHeader + i * sizeof(IMAGE_SECTION_HEADER));
- OUTPUT("\n\tSECTION : %s\n", (wchar_t*)pCurrentSectionHeader->Name);
- OUTPUT("\t\tMisc (PhysicalAddress) : 0x%X\n", (uintptr_t)pCurrentSectionHeader->Misc.PhysicalAddress);
- OUTPUT("\t\tMisc (VirtualSize) : 0x%X\n", (uintptr_t)pCurrentSectionHeader->Misc.VirtualSize);
- OUTPUT("\t\tVirtualAddress : 0x%X\n", (uintptr_t)pCurrentSectionHeader->VirtualAddress);
- OUTPUT("\t\tSizeOfRawData : 0x%X\n", (uintptr_t)pCurrentSectionHeader->SizeOfRawData);
- OUTPUT("\t\tPointerToRawData : 0x%X\n", (uintptr_t)pCurrentSectionHeader->PointerToRawData);
- OUTPUT("\t\tCharacteristics : 0x%X %s\n", (uintptr_t)pCurrentSectionHeader->Characteristics, GetSectionProtection(pCurrentSectionHeader->Characteristics));
- if (dImportAddress >= pCurrentSectionHeader->VirtualAddress && dImportAddress < pCurrentSectionHeader->VirtualAddress + pCurrentSectionHeader->Misc.VirtualSize) {
- pImageImportHeader = pCurrentSectionHeader;
- }
- }
- return pImageImportHeader;
- }
- void GetImports32(PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor, DWORD dRawOffset, const PIMAGE_SECTION_HEADER pImageImportSection) {
- OUTPUT("\n[+] IMPORTED DLL\n");
- while (pImageImportDescriptor->Name != 0) {
- OUTPUT("\n\tDLL NAME : %s\n", (wchar_t*)(dRawOffset + (pImageImportDescriptor->Name - pImageImportSection->VirtualAddress)));
- if (pImageImportDescriptor->OriginalFirstThunk == 0) {
- ++pImageImportDescriptor;
- continue;
- }
- auto pOriginalFirstThunk = reinterpret_cast<PIMAGE_THUNK_DATA32>(dRawOffset + (pImageImportDescriptor->OriginalFirstThunk - pImageImportSection->VirtualAddress));
- while (pOriginalFirstThunk->u1.AddressOfData != 0) {
- const auto pImageImportByName = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(dRawOffset + (pOriginalFirstThunk->u1.AddressOfData - pImageImportSection->VirtualAddress));
- if (pImageImportByName) {
- OUTPUT("\t\tFunction: %s\n", (char*)pImageImportByName->Name);
- }
- pOriginalFirstThunk++;
- }
- pImageImportDescriptor++;
- }
- }
- void GetImports64(PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor, DWORD dRawOffset, const PIMAGE_SECTION_HEADER pImageImportSection) {
- OUTPUT("\n[+] IMPORTED DLL\n");
- while (pImageImportDescriptor->Name != 0) {
- OUTPUT("\n\tDLL NAME : %s\n", (wchar_t*)(dRawOffset + (pImageImportDescriptor->Name - pImageImportSection->VirtualAddress)));
- if (pImageImportDescriptor->OriginalFirstThunk == 0) {
- ++pImageImportDescriptor;
- continue;
- }
- auto pOriginalFirstThunk = reinterpret_cast<PIMAGE_THUNK_DATA64>(dRawOffset + (pImageImportDescriptor->OriginalFirstThunk - pImageImportSection->VirtualAddress));
- while (pOriginalFirstThunk->u1.AddressOfData != 0) {
- const auto pImageImportByName = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(dRawOffset + (pOriginalFirstThunk->u1.AddressOfData - pImageImportSection->VirtualAddress));
- if (pImageImportByName) {
- OUTPUT("\t\tFunction: %s\n", (char*)pImageImportByName->Name);
- }
- pOriginalFirstThunk++;
- }
- pImageImportDescriptor++;
- }
- }
- //use above ^^ ALWAYS
- */
- /*
- // older-orig-deprecated vv
- // Main PE Analysis function
- void AnalyzePEFile(const wchar_t* filePathW)
- {
- //WCHAR filePathW[MAX_PATH];
- //MultiByteToWideChar(CP_ACP, 0, filePathA, -1, filePathW, MAX_PATH);
- OUTPUT("[+] Starting PE Analysis for: %s\n\n", filePathW);
- //AppendToOutput(L"[+] Starting PE Analysis for: %ls\n\n", filePathW);
- // Get file content
- LPVOID lpFileContent = GetFileContent(filePathW);
- if (!lpFileContent)
- {
- OUTPUT("[-] Failed to read file content!\n");
- return;
- }
- // Get DOS header
- const auto pImageDosHeader = static_cast<PIMAGE_DOS_HEADER>(lpFileContent);
- if (pImageDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
- {
- OUTPUT("[-] Invalid DOS signature!\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- return;
- }
- // Get NT headers
- const auto pImageNtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>((DWORD_PTR)lpFileContent + pImageDosHeader->e_lfanew);
- if (pImageNtHeaders->Signature != IMAGE_NT_SIGNATURE)
- {
- OUTPUT("[-] Invalid NT signature!\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- return;
- }
- // Display File Header information
- OUTPUT("[+] PE FILE HEADER\n");
- OUTPUT("\tMachine : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.Machine);
- OUTPUT("\tNumberOfSections : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.NumberOfSections);
- OUTPUT("\tTimeDateStamp : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.TimeDateStamp);
- OUTPUT("\tPointerToSymbolTable : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.PointerToSymbolTable);
- OUTPUT("\tNumberOfSymbols : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.NumberOfSymbols);
- OUTPUT("\tSizeOfOptionalHeader : 0x%X\n", (uintptr_t)pImageNtHeaders->FileHeader.SizeOfOptionalHeader);
- OUTPUT("\tCharacteristics : 0x%X %s\n\n",
- (uintptr_t)pImageNtHeaders->FileHeader.Characteristics,
- GetImageCharacteristics(pImageNtHeaders->FileHeader.Characteristics));
- // Display Optional Header information
- OUTPUT("[+] PE OPTIONAL HEADER\n");
- OUTPUT("\tMagic : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.Magic);
- OUTPUT("\tAddressOfEntryPoint : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.AddressOfEntryPoint);
- OUTPUT("\tImageBase : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.ImageBase);
- OUTPUT("\tSectionAlignment : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SectionAlignment);
- OUTPUT("\tFileAlignment : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.FileAlignment);
- OUTPUT("\tMajorOperatingSystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MajorOperatingSystemVersion);
- OUTPUT("\tMinorOperatingSystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MinorOperatingSystemVersion);
- OUTPUT("\tMajorImageVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MajorImageVersion);
- OUTPUT("\tMinorImageVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MinorImageVersion);
- OUTPUT("\tMajorSubsystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MajorSubsystemVersion);
- OUTPUT("\tMinorSubsystemVersion : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.MinorSubsystemVersion);
- OUTPUT("\tWin32VersionValue : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.Win32VersionValue);
- OUTPUT("\tSizeOfImage : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfImage);
- OUTPUT("\tSizeOfHeaders : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfHeaders);
- OUTPUT("\tCheckSum : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.CheckSum);
- OUTPUT("\tSubsystem : 0x%X %s\n",
- (uintptr_t)pImageNtHeaders->OptionalHeader.Subsystem,
- GetSubsystem(pImageNtHeaders->OptionalHeader.Subsystem));
- OUTPUT("\tDllCharacteristics : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.DllCharacteristics);
- OUTPUT("\tSizeOfStackReserve : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfStackReserve);
- OUTPUT("\tSizeOfStackCommit : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfStackCommit);
- OUTPUT("\tSizeOfHeapReserve : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfHeapReserve);
- OUTPUT("\tSizeOfHeapCommit : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.SizeOfHeapCommit);
- OUTPUT("\tLoaderFlags : 0x%X\n", (uintptr_t)pImageNtHeaders->OptionalHeader.LoaderFlags);
- OUTPUT("\tNumberOfRvaAndSizes : 0x%X\n\n", (uintptr_t)pImageNtHeaders->OptionalHeader.NumberOfRvaAndSizes);
- // Get Data Directories
- GetDataDirectories(&pImageNtHeaders->OptionalHeader.DataDirectory[0]);
- // Get the import section
- const auto pImageSectionHeader = reinterpret_cast<PIMAGE_SECTION_HEADER>(
- (DWORD_PTR)pImageNtHeaders + sizeof(IMAGE_NT_HEADERS));
- const auto pImageImportSection = GetSections(
- pImageSectionHeader,
- pImageNtHeaders->FileHeader.NumberOfSections,
- pImageNtHeaders->OptionalHeader.DataDirectory[1].VirtualAddress);
- if (!pImageImportSection)
- {
- OUTPUT("[-] Error: Could not find import section!\n");
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- return;
- }
- // Get imports based on architecture
- const auto pImageImportDescriptor = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(
- (DWORD_PTR)lpFileContent + pImageImportSection->PointerToRawData);
- if (pImageNtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
- {
- GetImports32(
- pImageImportDescriptor,
- (DWORD)lpFileContent + pImageImportSection->PointerToRawData,
- pImageImportSection);
- }
- else if (pImageNtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
- {
- GetImports64(
- pImageImportDescriptor,
- (DWORD)lpFileContent + pImageImportSection->PointerToRawData,
- pImageImportSection);
- }
- else
- {
- OUTPUT("[-] Unsupported architecture!\n");
- }
- // Cleanup
- HeapFree(GetProcessHeap(), 0, lpFileContent);
- // Update the GUI with the analysis results
- UpdateEditControl();
- }
- void GetDataDirectories(PIMAGE_DATA_DIRECTORY pImageDataDirectory)
- {
- OUTPUT("[+] PE DATA DIRECTORIES\n");
- for (int i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; ++i, ++pImageDataDirectory)
- {
- if (pImageDataDirectory->VirtualAddress == 0)
- continue;
- OUTPUT("\tDataDirectory (%s) VirtualAddress : 0x%X\n",
- GetDataDirectoryName(i),
- (uintptr_t)pImageDataDirectory->VirtualAddress);
- OUTPUT("\tDataDirectory (%s) Size : 0x%X\n\n",
- GetDataDirectoryName(i),
- (uintptr_t)pImageDataDirectory->Size);
- }
- }
- PIMAGE_SECTION_HEADER GetSections(const PIMAGE_SECTION_HEADER pImageSectionHeader,
- int NumberOfSections, DWORD dImportAddress)
- {
- PIMAGE_SECTION_HEADER pImageImportHeader = nullptr;
- OUTPUT("\n[+] PE IMAGE SECTIONS\n");
- for (int i = 0; i < NumberOfSections; ++i)
- {
- const auto pCurrentSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD_PTR)pImageSectionHeader +
- i * sizeof(IMAGE_SECTION_HEADER));
- OUTPUT("\n\tSECTION : %s\n", (wchar_t*)pCurrentSectionHeader->Name);
- OUTPUT("\t\tMisc (PhysicalAddress) : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->Misc.PhysicalAddress);
- OUTPUT("\t\tMisc (VirtualSize) : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->Misc.VirtualSize);
- OUTPUT("\t\tVirtualAddress : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->VirtualAddress);
- OUTPUT("\t\tSizeOfRawData : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->SizeOfRawData);
- OUTPUT("\t\tPointerToRawData : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->PointerToRawData);
- OUTPUT("\t\tPointerToRelocations : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->PointerToRelocations);
- OUTPUT("\t\tPointerToLinenumbers : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->PointerToLinenumbers);
- OUTPUT("\t\tNumberOfRelocations : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->NumberOfRelocations);
- OUTPUT("\t\tNumberOfLinenumbers : 0x%X\n",
- (uintptr_t)pCurrentSectionHeader->NumberOfLinenumbers);
- OUTPUT("\t\tCharacteristics : 0x%X %s\n",
- (uintptr_t)pCurrentSectionHeader->Characteristics,
- GetSectionProtection(pCurrentSectionHeader->Characteristics));
- if (dImportAddress >= pCurrentSectionHeader->VirtualAddress &&
- dImportAddress < pCurrentSectionHeader->VirtualAddress +
- pCurrentSectionHeader->Misc.VirtualSize)
- {
- pImageImportHeader = pCurrentSectionHeader;
- }
- }
- return pImageImportHeader;
- }
- void GetImports32(PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor,
- DWORD dRawOffset, const PIMAGE_SECTION_HEADER pImageImportSection)
- {
- OUTPUT("\n[+] IMPORTED DLL\n");
- while (pImageImportDescriptor->Name != 0)
- {
- OUTPUT("\n\tDLL NAME : %s\n",
- (wchar_t*)(dRawOffset + (pImageImportDescriptor->Name - pImageImportSection->VirtualAddress)));
- OUTPUT("\tCharacteristics : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->Characteristics - pImageImportSection->VirtualAddress)));
- OUTPUT("\tOriginalFirstThunk : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->OriginalFirstThunk - pImageImportSection->VirtualAddress)));
- OUTPUT("\tTimeDateStamp : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->TimeDateStamp - pImageImportSection->VirtualAddress)));
- OUTPUT("\tForwarderChain : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->ForwarderChain - pImageImportSection->VirtualAddress)));
- OUTPUT("\tFirstThunk : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->FirstThunk - pImageImportSection->VirtualAddress)));
- if (pImageImportDescriptor->OriginalFirstThunk == 0)
- {
- ++pImageImportDescriptor;
- continue;
- }
- auto pOriginalFirstThrunk = (PIMAGE_THUNK_DATA32)(dRawOffset +
- (pImageImportDescriptor->OriginalFirstThunk - pImageImportSection->VirtualAddress));
- OUTPUT("\n\tImported Functions : \n\n");
- while (pOriginalFirstThrunk->u1.AddressOfData != 0)
- {
- if (pOriginalFirstThrunk->u1.AddressOfData >= IMAGE_ORDINAL_FLAG32)
- {
- ++pOriginalFirstThrunk;
- continue;
- }
- const auto pImageImportByName = (PIMAGE_IMPORT_BY_NAME)(dRawOffset +
- (pOriginalFirstThrunk->u1.AddressOfData - pImageImportSection->VirtualAddress));
- if (pImageImportByName == nullptr)
- {
- ++pOriginalFirstThrunk;
- continue;
- }
- if (pOriginalFirstThrunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)
- {
- OUTPUT("\t\t0x%X (Ordinal) : %s\n",
- (uintptr_t)pOriginalFirstThrunk->u1.AddressOfData,
- (wchar_t*)((DWORD_PTR)dRawOffset + (pImageImportByName->Name - pImageImportSection->VirtualAddress)));
- }
- else
- {
- OUTPUT("\t\t%s\n",
- (wchar_t*)((DWORD_PTR)dRawOffset + (pImageImportByName->Name - pImageImportSection->VirtualAddress)));
- }
- ++pOriginalFirstThrunk;
- }
- ++pImageImportDescriptor;
- }
- }
- void GetImports64(PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor,
- DWORD dRawOffset, const PIMAGE_SECTION_HEADER pImageImportSection)
- {
- OUTPUT("\n[+] IMPORTED DLL\n");
- while (pImageImportDescriptor->Name != 0)
- {
- OUTPUT("\n\tDLL NAME : %s\n",
- (wchar_t*)(dRawOffset + (pImageImportDescriptor->Name - pImageImportSection->VirtualAddress)));
- OUTPUT("\tCharacteristics : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->Characteristics - pImageImportSection->VirtualAddress)));
- OUTPUT("\tOriginalFirstThunk : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->OriginalFirstThunk - pImageImportSection->VirtualAddress)));
- OUTPUT("\tTimeDateStamp : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->TimeDateStamp - pImageImportSection->VirtualAddress)));
- OUTPUT("\tForwarderChain : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->ForwarderChain - pImageImportSection->VirtualAddress)));
- OUTPUT("\tFirstThunk : 0x%X\n",
- (uintptr_t)(dRawOffset + (pImageImportDescriptor->FirstThunk - pImageImportSection->VirtualAddress)));
- if (pImageImportDescriptor->OriginalFirstThunk == 0)
- {
- ++pImageImportDescriptor;
- continue;
- }
- auto pOriginalFirstThrunk = (PIMAGE_THUNK_DATA64)(dRawOffset +
- (pImageImportDescriptor->OriginalFirstThunk - pImageImportSection->VirtualAddress));
- OUTPUT("\n\tImported Functions : \n\n");
- while (pOriginalFirstThrunk->u1.AddressOfData != 0)
- {
- if (pOriginalFirstThrunk->u1.AddressOfData >= IMAGE_ORDINAL_FLAG64)
- {
- ++pOriginalFirstThrunk;
- continue;
- }
- const auto pImageImportByName = (PIMAGE_IMPORT_BY_NAME)((DWORD_PTR)dRawOffset +
- (pOriginalFirstThrunk->u1.AddressOfData - pImageImportSection->VirtualAddress));
- if (pImageImportByName == nullptr)
- {
- ++pOriginalFirstThrunk;
- continue;
- }
- if (pOriginalFirstThrunk->u1.Ordinal & IMAGE_ORDINAL_FLAG64)
- {
- OUTPUT("\t\t0x%llX (Ordinal) : %s\n",
- pOriginalFirstThrunk->u1.AddressOfData,
- (wchar_t*)((DWORD_PTR)dRawOffset + (pImageImportByName->Name - pImageImportSection->VirtualAddress)));
- }
- else
- {
- OUTPUT("\t\t%s\n",
- (wchar_t*)((DWORD_PTR)dRawOffset + (pImageImportByName->Name - pImageImportSection->VirtualAddress)));
- }
- ++pOriginalFirstThrunk;
- }
- ++pImageImportDescriptor;
- }
- }
- // older-orig-deprecated ^^
- */
- //filePathW
- //lpFilePath
- HANDLE GetFileContent(const wchar_t* lpFilePath) {
- HANDLE hFile = CreateFileW(lpFilePath, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
- if (hFile == INVALID_HANDLE_VALUE) return nullptr;
- DWORD fileSize = GetFileSize(hFile, nullptr);
- auto lpFileContent = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, fileSize);
- DWORD bytesRead;
- ReadFile(hFile, lpFileContent, fileSize, &bytesRead, nullptr);
- CloseHandle(hFile);
- return lpFileContent;
- }
- void UpdateEditControl() {
- SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
- SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
- SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement