alien_fx_fiend

Crashing Even /w You.com Claude Fixes Implemented Herein

Dec 29th, 2024 (edited)
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 111.88 KB | Source Code | 0 0
  1. ===++++ main.cpp +++===
  2. #define STRICT
  3. #define WIN32_LEAN_AND_MEAN
  4. #define DEBUG_OUTPUT(format, ...) \
  5.     do { \
  6.         OUTPUT("[DEBUG] %s:%d - " format "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  7.     } while(0)
  8. #ifndef OUTPUT
  9. #define OUTPUT(format, ...) wprintf(L##format, ##__VA_ARGS__)
  10. #endif
  11. #include <Windows.h>
  12. #include <winternl.h>
  13. #include <CommCtrl.h>
  14. #include <commdlg.h>
  15. #include <string>
  16. #include <strsafe.h>
  17. #include <sstream>
  18. #include <iomanip>
  19. #include <stdio.h>
  20. #include <vector>
  21. #include <shellapi.h>
  22. //#include "helpers.h"
  23. #include "PEHeaders.h"
  24. #include "resource.h"
  25. #pragma comment(lib, "comctl32.lib")
  26.  
  27. //namespace was here
  28.  
  29. // Window defines
  30. #define WINDOW_CLASS_NAME L"PEAnalyzerWindow"
  31. #define OUTPUT(format, ...) AppendToOutput(L##format, ##__VA_ARGS__)
  32. #define WINDOW_WIDTH    1024
  33. #define WINDOW_HEIGHT   768
  34. #define EDIT_MARGIN    10
  35.  
  36. // Global variables
  37. HWND g_hMainWindow = NULL;
  38. HWND g_hEditControl = NULL;
  39. HWND g_hStatusBar = NULL;
  40. HWND g_hProgressBar = NULL;
  41. HFONT g_hFont = NULL;
  42. std::wstringstream g_OutputText;
  43. std::vector<wchar_t> g_OutputBuffer;
  44. std::wstring tempBuffer;
  45. WCHAR filePathW[MAX_PATH];
  46.  
  47. // Resource parsing constants
  48. static const wchar_t* RESOURCE_TYPES[] = {
  49.     L"Unknown",     L"Cursor",      L"Bitmap",      L"Icon",
  50.     L"Menu",        L"Dialog",      L"String",      L"FontDir",
  51.     L"Font",        L"Accelerator", L"RCData",      L"MessageTable",
  52.     L"GroupCursor", L"GroupIcon",   L"Version",     L"DlgInclude"
  53. };
  54.  
  55. //adding structs here now
  56.  
  57. enum class FileValidationResult {
  58.     Valid,
  59.     InvalidPath,
  60.     FileNotFound,
  61.     AccessDenied,
  62.     UnsupportedType
  63. };
  64.  
  65. // Forward declarations for global functions
  66. void UpdateEditControl();
  67. void AppendToOutput(const wchar_t* format, ...);
  68. void SetStatusText(const wchar_t* text);
  69. void ShowProgress(int percentage);
  70. void OpenFileDialog(HWND hwnd);
  71. void AnalyzePEFile(const wchar_t* filePathW);
  72. //analyzepefile 4wd func
  73. HANDLE GetFileContent(const wchar_t* lpFilePath);
  74. void OpenFileDialog(HWND hwnd); // Add these in the global scope, before any namespace declarations
  75.  
  76. // GUI-related forward declarations
  77. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
  78. LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,
  79.     LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
  80. void CreateMainWindow(HINSTANCE hInstance);
  81. void InitializeControls(HWND hwnd);
  82. void AddMenus(HWND hwnd);
  83. //void SetStatusText(const wchar_t* text);
  84. //void ShowProgress(int percentage);
  85. //void UpdateEditControl();    
  86. DWORD GetFileSizeCustom(const wchar_t* filePath);
  87.  
  88. //bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders);
  89.  
  90.  
  91. //using namespace std;
  92. //using namespace PEParser;
  93. //using namespace PEHelpers;
  94.  
  95. //namespace PEParser {
  96.  
  97. //struct PEAnalyzer;  // Forward declaration
  98. class FileMapper;
  99. FileValidationResult ValidatePEFile(const wchar_t* filePath);
  100. bool InitializePEAnalyzer(PEAnalyzer& analyzer, const wchar_t* filePath);
  101. //class FileValidationResult ValidatePEFile(const wchar_t* filePath);
  102. void ParseSections(const PEAnalyzer& analyzer); //forwarddeclare parse+ bring namespace up
  103. void ParseImportDirectory(const PEAnalyzer& analyzer);
  104. void ParseExportDirectory(const PEAnalyzer& analyzer);
  105. void ParseResourceDirectory(const PEAnalyzer& analyzer);
  106. void ParseDebugDirectory(const PEAnalyzer& analyzer);
  107. void AnalyzeHeaders(const PEAnalyzer& analyzer);
  108. void AnalyzeDataDirectories(const PEAnalyzer& analyzer);
  109. //bool InitializePEAnalyzer(PEAnalyzer& analyzer, const wchar_t* filePath);
  110.  
  111. //newglobals
  112. void ParseNTHeader64(const PEAnalyzer& analyzer);
  113. void ParseNTHeader32(const PEAnalyzer& analyzer);
  114. void ParseImportFunctions32(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc);
  115. void ParseImportFunctions64(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc);
  116. void ParseExportedFunctions(const PEAnalyzer& analyzer, PIMAGE_EXPORT_DIRECTORY pExportDir,
  117.     PDWORD pFunctions, PDWORD pNames, PWORD pOrdinals);
  118. void ProcessResourceDirectory(
  119.     PIMAGE_RESOURCE_DIRECTORY resDir,
  120.     int level,
  121.     const wchar_t* type,
  122.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  123.     const PEAnalyzer& analyzer);
  124. void ProcessNamedResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  125.     int level, PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  126.     const PEAnalyzer& analyzer);
  127. void ProcessIdResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  128.     int level, const wchar_t* type,
  129.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  130.     const PEAnalyzer& analyzer);
  131. void ProcessResourceSubdirectory(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  132.     int level, const wchar_t* type,
  133.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  134.     const PEAnalyzer& analyzer);
  135. void ProcessResourceData(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  136.     int level, const wchar_t* type,
  137.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  138.     const PEAnalyzer& analyzer);
  139. void ProcessDebugEntry(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer);
  140. void ProcessRSDSDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  141.     const PEAnalyzer& analyzer);
  142. void ProcessCodeViewDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer);
  143. void ProcessNB10DebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  144.     const PEAnalyzer& analyzer);
  145. //void ParseImportDirectory(const PEAnalyzer& analyzer);
  146. //void ParseExportDirectory(const PEAnalyzer& analyzer);
  147. //DWORD GetFileSizeCustom(const wchar_t* filePath);
  148. //endnewglobals
  149.  
  150. //using namespace std;
  151. //using namespace PEHelpers;
  152. //struct was here
  153.  
  154.  
  155. // File mapping helper class
  156. class FileMapper {
  157. private:
  158.     HANDLE hFile;
  159.     HANDLE hMapping;
  160.     LPVOID lpView;
  161.  
  162. public:
  163.     FileMapper() : hFile(INVALID_HANDLE_VALUE), hMapping(nullptr), lpView(nullptr) {}
  164.     ~FileMapper() { Cleanup(); }
  165.  
  166.     void Cleanup() {
  167.         if (lpView) {
  168.             UnmapViewOfFile(lpView);
  169.             lpView = nullptr;
  170.         }
  171.         if (hMapping) {
  172.             CloseHandle(hMapping);
  173.             hMapping = nullptr;
  174.         }
  175.         if (hFile != INVALID_HANDLE_VALUE) {
  176.             CloseHandle(hFile);
  177.             hFile = INVALID_HANDLE_VALUE;
  178.         }
  179.     }
  180.  
  181.     bool Initialize(const wchar_t* path) {
  182.         Cleanup();
  183.  
  184.         // First open and map the file normally to get its size
  185.         hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
  186.             nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  187.  
  188.         if (hFile == INVALID_HANDLE_VALUE) {
  189.             DWORD error = GetLastError();
  190.             OUTPUT("[-] File Open Error: %d\n", error);
  191.             return false;
  192.         }
  193.  
  194.         LARGE_INTEGER fileSize;
  195.         if (!GetFileSizeEx(hFile, &fileSize)) {
  196.             DWORD error = GetLastError();
  197.             OUTPUT("[-] Cannot get file size. Error: %d\n", error);
  198.             Cleanup();
  199.             return false;
  200.         }
  201.  
  202.         // Create mapping without SEC_IMAGE first
  203.         hMapping = CreateFileMappingW(hFile, nullptr, PAGE_READONLY,
  204.             fileSize.HighPart, fileSize.LowPart, nullptr);
  205.  
  206.         if (!hMapping) {
  207.             DWORD error = GetLastError();
  208.             OUTPUT("[-] File Mapping Creation Failed. Error: %d\n", error);
  209.             Cleanup();
  210.             return false;
  211.         }
  212.  
  213.         lpView = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  214.  
  215.         if (!lpView) {
  216.             DWORD error = GetLastError();
  217.             OUTPUT("[-] MapViewOfFile Failed. Error: %d\n", error);
  218.             Cleanup();
  219.             return false;
  220.         }
  221.  
  222.         return true;
  223.     }
  224.  
  225.     LPVOID GetView() const { return lpView; }
  226. };
  227.  
  228. FileValidationResult ValidatePEFile(const wchar_t* filePath) {
  229.     if (!filePath || wcslen(filePath) == 0) {
  230.         OUTPUT("[-] Null or empty file path\n");
  231.         return FileValidationResult::InvalidPath;
  232.     }
  233.  
  234.     // Check file extension
  235.     const wchar_t* ext = wcsrchr(filePath, L'.');
  236.     if (!ext || (wcscmp(ext, L".exe") != 0 && wcscmp(ext, L".dll") != 0)) {
  237.         OUTPUT("[-] Unsupported file type. Only .exe and .dll are supported\n");
  238.         return FileValidationResult::UnsupportedType;
  239.     }
  240.  
  241.     // Detailed file access check
  242.     HANDLE hFile = CreateFileW(
  243.         filePath,
  244.         GENERIC_READ,
  245.         FILE_SHARE_READ | FILE_SHARE_WRITE,
  246.         NULL,
  247.         OPEN_EXISTING,
  248.         FILE_ATTRIBUTE_NORMAL,
  249.         NULL
  250.     );
  251.  
  252.     if (hFile == INVALID_HANDLE_VALUE) {
  253.         DWORD error = GetLastError();
  254.         switch (error) {
  255.         case ERROR_FILE_NOT_FOUND:
  256.             OUTPUT("[-] File not found: %s\n", filePath);
  257.             return FileValidationResult::FileNotFound;
  258.         case ERROR_ACCESS_DENIED:
  259.             OUTPUT("[-] Access denied. Check file permissions: %s\n", filePath);
  260.             return FileValidationResult::AccessDenied;
  261.         default:
  262.             OUTPUT("[-] File open error %d: %s\n", error, filePath);
  263.             return FileValidationResult::InvalidPath;
  264.         }
  265.     }
  266.  
  267.     // Additional checks
  268.     LARGE_INTEGER fileSize;
  269.     if (!GetFileSizeEx(hFile, &fileSize)) {
  270.         CloseHandle(hFile);
  271.         OUTPUT("[-] Cannot determine file size\n");
  272.         return FileValidationResult::InvalidPath;
  273.     }
  274.  
  275.     CloseHandle(hFile);
  276.     return FileValidationResult::Valid;
  277. }
  278.  
  279. // Initialization function
  280. bool InitializePEAnalyzer(PEAnalyzer& analyzer, const wchar_t* filePath) {
  281.     FileValidationResult validationResult = ValidatePEFile(filePath);
  282.     if (validationResult != FileValidationResult::Valid) {
  283.         OUTPUT("[-] File validation failed with code: %d\n",
  284.             static_cast<int>(validationResult));
  285.         return false;
  286.     }
  287.  
  288.     FileMapper mapper;
  289.     if (!mapper.Initialize(filePath)) {
  290.         OUTPUT("[-] Failed to map file. Detailed error in FileMapper\n");
  291.         return false;
  292.     }
  293.  
  294.     analyzer.lpFileContent = mapper.GetView();
  295.     analyzer.fileSize = GetFileSizeCustom(filePath);
  296.  
  297.     // Comprehensive PE signature validation
  298.         if (!analyzer.lpFileContent || analyzer.fileSize == 0) {
  299.         OUTPUT("[-] Memory mapping failed or file size is zero\n");
  300.         return false;
  301.     }
  302.  
  303.         // Add bounds checking
  304.         if (analyzer.fileSize < sizeof(IMAGE_DOS_HEADER)) {
  305.             OUTPUT("[-] File too small to contain DOS header\n");
  306.             return false;
  307.         }
  308.  
  309.     // DOS Header validation with extensive checks
  310.         analyzer.pDosHeader = static_cast<PIMAGE_DOS_HEADER>(analyzer.lpFileContent);
  311.  
  312.         // Validate DOS header
  313.         if (!IsSafeToRead(analyzer, analyzer.pDosHeader, sizeof(IMAGE_DOS_HEADER))) {
  314.             OUTPUT("[-] Invalid DOS header access\n");
  315.             return false;
  316.         }
  317.  
  318.     // More robust DOS signature check
  319.         if (analyzer.pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
  320.             OUTPUT("[-] Invalid DOS signature: 0x%X (Expected 0x%X)\n",
  321.                 analyzer.pDosHeader->e_magic, IMAGE_DOS_SIGNATURE);
  322.             return false;
  323.         }
  324.  
  325.     // Validate e_lfanew with more checks
  326.     if (analyzer.pDosHeader->e_lfanew >= analyzer.fileSize ||
  327.         analyzer.pDosHeader->e_lfanew < sizeof(IMAGE_DOS_HEADER)) {
  328.         OUTPUT("[-] Invalid e_lfanew value: 0x%X\n", analyzer.pDosHeader->e_lfanew);
  329.         return false;
  330.     }
  331.  
  332.     /*analyzer.lpFileContent = mapper.GetView();
  333.     if (!analyzer.lpFileContent) {
  334.         OUTPUT("[-] Failed to get file view. Memory mapping issue.\n");
  335.         return false;
  336.     }
  337.  
  338.     analyzer.fileSize = GetFileSizeCustom(filePath);
  339.     if (!analyzer.fileSize) {
  340.         OUTPUT("[-] Unable to determine file size. File might be empty.\n");
  341.         return false;
  342.     }*/
  343.  
  344.     // Validate file content
  345.     /*if (analyzer.fileSize < sizeof(IMAGE_DOS_HEADER)) {
  346.         OUTPUT("[-] File too small to be a valid PE\n");
  347.         return false;
  348.     }
  349.  
  350.     analyzer.pDosHeader = static_cast<PIMAGE_DOS_HEADER>(analyzer.lpFileContent);
  351.     if (!analyzer.pDosHeader || analyzer.pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
  352.         OUTPUT("[-] Invalid DOS signature\n");
  353.         return false;
  354.     }
  355.  
  356.     // Validate e_lfanew
  357.     if (analyzer.pDosHeader->e_lfanew >= analyzer.fileSize ||
  358.         analyzer.pDosHeader->e_lfanew < sizeof(IMAGE_DOS_HEADER)) {
  359.         OUTPUT("[-] Invalid e_lfanew value\n");
  360.         return false;
  361.     }*/
  362.  
  363.     // Validate NT Headers location
  364.     LONG ntHeaderOffset = analyzer.pDosHeader->e_lfanew;
  365.     if (ntHeaderOffset <= 0 ||
  366.         ntHeaderOffset >= analyzer.fileSize ||
  367.         ntHeaderOffset < sizeof(IMAGE_DOS_HEADER)) {
  368.         OUTPUT("[-] Invalid NT Headers offset: 0x%X\n", ntHeaderOffset);
  369.         return false;
  370.     }
  371.  
  372.     // NT Headers signature validation
  373.     auto pNtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(
  374.         static_cast<BYTE*>(analyzer.lpFileContent) + ntHeaderOffset);
  375.  
  376.     if (pNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
  377.         OUTPUT("[-] Invalid NT signature: 0x%X (Expected 0x%X)\n",
  378.             pNtHeaders->Signature,
  379.             IMAGE_NT_SIGNATURE);
  380.         return false;
  381.     }
  382.  
  383.     /*if (IsBadReadPtr(pNtHeaders, sizeof(IMAGE_NT_HEADERS)) ||
  384.         pNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
  385.         OUTPUT("[-] Invalid NT signature\n");
  386.         return false;
  387.     }*/
  388.  
  389.     // Determine architecture with additional safety checks
  390.     WORD magicNumber = pNtHeaders->OptionalHeader.Magic;
  391.     analyzer.is64Bit = (magicNumber == IMAGE_NT_OPTIONAL_HDR64_MAGIC);
  392.  
  393.     try {
  394.         if (analyzer.is64Bit) {
  395.             analyzer.pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  396.             analyzer.pNtHeaders32 = nullptr;
  397.  
  398.             // Validate 64-bit optional header
  399.             if (pNtHeaders->FileHeader.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER64)) {
  400.                 OUTPUT("[-] Invalid 64-bit optional header size\n");
  401.                 return false;
  402.             }
  403.         }
  404.         else {
  405.             analyzer.pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  406.             analyzer.pNtHeaders64 = nullptr;
  407.  
  408.             // Validate 32-bit optional header
  409.             if (pNtHeaders->FileHeader.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)) {
  410.                 OUTPUT("[-] Invalid 32-bit optional header size\n");
  411.                 return false;
  412.             }
  413.         }
  414.     }
  415.     catch (...) {
  416.         OUTPUT("[-] Exception during architecture determination\n");
  417.         return false;
  418.     }
  419.  
  420.     return true;
  421. }
  422.  
  423. // Helper function for file size
  424. DWORD GetFileSizeCustom(const wchar_t* filePath) {
  425.     HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ,
  426.         nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  427.     if (hFile == INVALID_HANDLE_VALUE) return 0;
  428.  
  429.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  430.     CloseHandle(hFile);
  431.     return fileSize;
  432. } //removing other not this duplicate
  433.  
  434. // Main analysis function
  435. void AnalyzePEFile(const wchar_t* filePathW) {
  436.     if (!filePathW || wcslen(filePathW) == 0) {
  437.         OUTPUT("[-] Invalid file path\n");
  438.         SetStatusText(L"Invalid file path!");
  439.         ShowProgress(0);
  440.         return;
  441.     }
  442.  
  443.     /* // Check file extension
  444.     const wchar_t* ext = wcsrchr(filePathW, L'.');
  445.     if (!ext || (wcscmp(ext, L".exe") != 0 && wcscmp(ext, L".dll") != 0)) {
  446.         OUTPUT("[-] Unsupported file type. Use .exe or .dll\n");
  447.         SetStatusText(L"Unsupported file type!");
  448.         ShowProgress(0);
  449.         return;
  450.     } */
  451.  
  452.     /* // Check if file exists
  453.     HANDLE hFile = CreateFileW(filePathW, GENERIC_READ, FILE_SHARE_READ,
  454.         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  455.     if (hFile == INVALID_HANDLE_VALUE) {
  456.         DWORD error = GetLastError();
  457.         OUTPUT("[-] Cannot open file. Error code: %d\n", error);
  458.         SetStatusText(L"Failed to open file!");
  459.         ShowProgress(0);
  460.         return;
  461.     }
  462.     CloseHandle(hFile); */
  463.  
  464.     // Reset and prepare for analysis
  465.     g_OutputText.str(L"");
  466.     g_OutputText.clear();
  467.     UpdateEditControl();
  468.  
  469.     try {
  470.         OUTPUT("[+] Starting PE Analysis for: %s\n\n", filePathW);
  471.         SetStatusText(L"Analyzing PE File...");
  472.         ShowProgress(10);
  473.     //ShowProgress(10);
  474.  
  475.         PEAnalyzer analyzer;
  476.         if (!InitializePEAnalyzer(analyzer, filePathW)) {
  477.             OUTPUT("[-] PE Initialization Failed\n");
  478.             SetStatusText(L"PE Analysis Failed");
  479.             ShowProgress(0);
  480.             UpdateEditControl();
  481.             return;
  482.         }
  483.  
  484.         // Add safety check
  485.         if (!analyzer.lpFileContent || !analyzer.pDosHeader) {
  486.             OUTPUT("[-] Invalid PE file structure\n");
  487.             SetStatusText(L"Invalid PE File");
  488.             ShowProgress(0);
  489.             UpdateEditControl();
  490.             return;
  491.         }
  492.  
  493.         // Detailed logging for architecture
  494.         OUTPUT("[+] File Architecture: %s\n",
  495.             analyzer.is64Bit ? "64-bit" : "32-bit");
  496.  
  497.         // Show initial progress
  498.         //ShowProgress(10);
  499.  
  500.         /* // Add null checks before processing
  501.         if (!analyzer.lpFileContent) {
  502.             OUTPUT("[-] No file content available\n");
  503.             SetStatusText(L"Failed to read file content!");
  504.             ShowProgress(0);
  505.             return;
  506.         }
  507.  
  508.         // Inside AnalyzePEFile, before parsing headers
  509.         if (analyzer.is64Bit) {
  510.             if (!PEHelpers::ValidateFileSize(analyzer.pNtHeaders64->OptionalHeader.SizeOfImage, analyzer.fileSize)) {
  511.                 OUTPUT("[-] PE file size mismatch with 64-bit image size!\n");
  512.                 throw std::runtime_error("Invalid file size or PE image");
  513.             }
  514.         }
  515.         else {
  516.             if (!PEHelpers::ValidateFileSize(analyzer.pNtHeaders32->OptionalHeader.SizeOfImage, analyzer.fileSize)) {
  517.                 OUTPUT("[-] PE file size mismatch with 32-bit image size!\n");
  518.                 throw std::runtime_error("Invalid file size or PE image");
  519.             }
  520.         }*/
  521.  
  522.         // Wrap each analysis step in its own try-catch
  523.         // Basic headers analysis
  524.         try {
  525.             ShowProgress(20);
  526.             AnalyzeHeaders(analyzer);
  527.         }
  528.         catch (const std::exception& ex) {
  529.             OUTPUT("[-] Header Analysis Error: %s\n", ex.what());
  530.         }
  531.         //AnalyzeHeaders(analyzer);
  532.  
  533.         // Data directories
  534.         try {
  535.             ShowProgress(30);
  536.             AnalyzeDataDirectories(analyzer);
  537.         }
  538.         catch (const std::exception& ex) {
  539.             OUTPUT("[-] Data Directories Analysis Error: %s\n", ex.what());
  540.         }
  541.         //AnalyzeDataDirectories(analyzer);
  542.  
  543.         // Parse sections
  544.         try {
  545.             ShowProgress(40);
  546.             ParseSections(analyzer);
  547.         }
  548.         catch (const std::exception& ex) {
  549.             OUTPUT("[-] Sections Parsing Error: %s\n", ex.what());
  550.         }
  551.  
  552.         //ParseSections(analyzer);
  553.  
  554.         // Parse imports
  555.         try {
  556.             ShowProgress(50);
  557.             ParseImportDirectory(analyzer);
  558.         }
  559.         catch (const std::exception& ex) {
  560.             OUTPUT("[-] Import Directory Parsing Error: %s\n", ex.what());
  561.         }
  562.         //ParseImportDirectory(analyzer);
  563.  
  564.         // Parse exports
  565.         try {
  566.             ShowProgress(60);
  567.             ParseExportDirectory(analyzer);
  568.         }
  569.         catch (const std::exception& ex) {
  570.             OUTPUT("[-] Export Directory Parsing Error: %s\n", ex.what());
  571.         }
  572.         //ParseExportDirectory(analyzer);
  573.  
  574.         // Parse resources
  575.         try {
  576.             ShowProgress(70);
  577.             ParseResourceDirectory(analyzer);
  578.         }
  579.         catch (const std::exception& ex) {
  580.             OUTPUT("[-] Resource Directory Parsing Error: %s\n", ex.what());
  581.         }
  582.         //ParseResourceDirectory(analyzer);
  583.  
  584.         // Parse debug info
  585.         try {
  586.             ShowProgress(80);
  587.             ParseDebugDirectory(analyzer);
  588.         }
  589.         catch (const std::exception& ex) {
  590.             OUTPUT("[-] Debug Directory Parsing Error: %s\n", ex.what());
  591.         }
  592.         //ParseDebugDirectory(analyzer);
  593.  
  594.         ShowProgress(100);
  595.         SetStatusText(L"Analysis Complete");
  596.     }
  597.     //}
  598.     catch (const std::exception& ex) {
  599.         OUTPUT("[-] Exception during analysis: %s\n", ex.what());
  600.         SetStatusText(L"Analysis Failed");
  601.         ShowProgress(0);
  602.     }
  603.     catch (...) {
  604.         OUTPUT("[-] Unknown error during analysis\n");
  605.         SetStatusText(L"Analysis Failed");
  606.         ShowProgress(0);
  607.     }
  608.     /*catch (const std::exception& ex) {
  609.         OUTPUT("[-] Exception during analysis: %s\n", ex.what());
  610.         SetStatusText(L"Analysis failed due to error.");
  611.         ShowProgress(0);
  612.         return;
  613.     }*/ //newly commented out
  614.     /*catch (const std::exception& e) {
  615.         OUTPUT("[-] Error during analysis: %s\n", e.what());
  616.         SetStatusText(L"Analysis failed!");
  617.     }*/
  618.  
  619.     //ShowWindow(g_hProgressBar, SW_HIDE);
  620.     // Ensure edit control is updated
  621.     UpdateEditControl();
  622.     //analyzer.~PEAnalyzer(); // Explicit call to the destructor if not already invoked
  623. }
  624.  
  625. //amalgamating parsing funcs here experimental
  626.  
  627.     // Header analysis function
  628. void AnalyzeHeaders(const PEAnalyzer& analyzer) {
  629.     if (!analyzer.lpFileContent || !analyzer.pDosHeader) {
  630.         throw std::runtime_error("Invalid PE headers");
  631.     }
  632.  
  633.     OUTPUT("[+] PE IMAGE INFORMATION\n\n");
  634.     OUTPUT("[+] Architecture: %s\n\n", analyzer.is64Bit ? "x64" : "x86");
  635.  
  636.     // DOS Header
  637.     OUTPUT("[+] DOS HEADER\n");
  638.     OUTPUT("\te_magic    : 0x%X\n", analyzer.pDosHeader->e_magic);
  639.     OUTPUT("\te_cblp     : 0x%X\n", analyzer.pDosHeader->e_cblp);
  640.     OUTPUT("\te_cp       : 0x%X\n", analyzer.pDosHeader->e_cp);
  641.     OUTPUT("\te_crlc     : 0x%X\n", analyzer.pDosHeader->e_crlc);
  642.     OUTPUT("\te_cparhdr  : 0x%X\n", analyzer.pDosHeader->e_cparhdr);
  643.     OUTPUT("\te_minalloc : 0x%X\n", analyzer.pDosHeader->e_minalloc);
  644.     OUTPUT("\te_maxalloc : 0x%X\n", analyzer.pDosHeader->e_maxalloc);
  645.     OUTPUT("\te_ss       : 0x%X\n", analyzer.pDosHeader->e_ss);
  646.     OUTPUT("\te_sp       : 0x%X\n", analyzer.pDosHeader->e_sp);
  647.     OUTPUT("\te_csum     : 0x%X\n", analyzer.pDosHeader->e_csum);
  648.     OUTPUT("\te_ip       : 0x%X\n", analyzer.pDosHeader->e_ip);
  649.     OUTPUT("\te_cs       : 0x%X\n", analyzer.pDosHeader->e_cs);
  650.     OUTPUT("\te_lfarlc   : 0x%X\n", analyzer.pDosHeader->e_lfarlc);
  651.     OUTPUT("\te_ovno     : 0x%X\n", analyzer.pDosHeader->e_ovno);
  652.     OUTPUT("\te_oemid    : 0x%X\n", analyzer.pDosHeader->e_oemid);
  653.     OUTPUT("\te_oeminfo  : 0x%X\n", analyzer.pDosHeader->e_oeminfo);
  654.     OUTPUT("\te_lfanew   : 0x%X\n\n", analyzer.pDosHeader->e_lfanew);
  655.  
  656.     // NT Headers
  657.     if (analyzer.is64Bit && analyzer.pNtHeaders64) {
  658.         ParseNTHeader64(analyzer);
  659.         //AnalyzeNTHeaders64(analyzer);
  660.     }
  661.     else if (analyzer.pNtHeaders32) {
  662.         ParseNTHeader32(analyzer);
  663.         //AnalyzeNTHeaders32(analyzer);
  664.     }
  665.     else {
  666.         throw std::runtime_error("Invalid NT headers");
  667.     }
  668. }
  669.  
  670. void ParseNTHeader32(const PEAnalyzer& analyzer) {
  671.     if (!analyzer.pNtHeaders32) {
  672.         throw std::runtime_error("Invalid NT headers");
  673.     }
  674.  
  675.     OUTPUT("[+] NT HEADER (32-bit)\n");
  676.     OUTPUT("\tSignature: 0x%X\n\n", analyzer.pNtHeaders32->Signature);
  677.  
  678.     // File Header
  679.     OUTPUT("[+] FILE HEADER\n");
  680.     OUTPUT("\tMachine: 0x%X\n", analyzer.pNtHeaders32->FileHeader.Machine);
  681.     OUTPUT("\tNumberOfSections: 0x%X\n", analyzer.pNtHeaders32->FileHeader.NumberOfSections);
  682.     OUTPUT("\tTimeDateStamp: 0x%X\n", analyzer.pNtHeaders32->FileHeader.TimeDateStamp);
  683.     OUTPUT("\tPointerToSymbolTable: 0x%X\n", analyzer.pNtHeaders32->FileHeader.PointerToSymbolTable);
  684.     OUTPUT("\tNumberOfSymbols: 0x%X\n", analyzer.pNtHeaders32->FileHeader.NumberOfSymbols);
  685.     OUTPUT("\tSizeOfOptionalHeader: 0x%X\n", analyzer.pNtHeaders32->FileHeader.SizeOfOptionalHeader);
  686.     OUTPUT("\tCharacteristics: 0x%X\n\n", analyzer.pNtHeaders32->FileHeader.Characteristics);
  687.  
  688.     // Optional Header
  689.     OUTPUT("[+] OPTIONAL HEADER\n");
  690.     OUTPUT("\tMagic: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.Magic);
  691.     OUTPUT("\tAddressOfEntryPoint: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.AddressOfEntryPoint);
  692.     OUTPUT("\tImageBase: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.ImageBase);
  693.     OUTPUT("\tSectionAlignment: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.SectionAlignment);
  694.     OUTPUT("\tFileAlignment: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.FileAlignment);
  695.     OUTPUT("\tSizeOfImage: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.SizeOfImage);
  696.     OUTPUT("\tSizeOfHeaders: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.SizeOfHeaders);
  697.     OUTPUT("\tSubsystem: 0x%X\n\n", analyzer.pNtHeaders32->OptionalHeader.Subsystem);
  698. }
  699.  
  700. void ParseNTHeader64(const PEAnalyzer& analyzer) {
  701.     if (!analyzer.pNtHeaders64) {
  702.         throw std::runtime_error("Invalid NT headers");
  703.     }
  704.  
  705.     OUTPUT("[+] NT HEADER (64-bit)\n");
  706.     OUTPUT("\tSignature: 0x%X\n\n", analyzer.pNtHeaders64->Signature);
  707.  
  708.     // File Header
  709.     OUTPUT("[+] FILE HEADER\n");
  710.     OUTPUT("\tMachine: 0x%X\n", analyzer.pNtHeaders64->FileHeader.Machine);
  711.     OUTPUT("\tNumberOfSections: 0x%X\n", analyzer.pNtHeaders64->FileHeader.NumberOfSections);
  712.     OUTPUT("\tTimeDateStamp: 0x%X\n", analyzer.pNtHeaders64->FileHeader.TimeDateStamp);
  713.     OUTPUT("\tPointerToSymbolTable: 0x%X\n", analyzer.pNtHeaders64->FileHeader.PointerToSymbolTable);
  714.     OUTPUT("\tNumberOfSymbols: 0x%X\n", analyzer.pNtHeaders64->FileHeader.NumberOfSymbols);
  715.     OUTPUT("\tSizeOfOptionalHeader: 0x%X\n", analyzer.pNtHeaders64->FileHeader.SizeOfOptionalHeader);
  716.     OUTPUT("\tCharacteristics: 0x%X\n\n", analyzer.pNtHeaders64->FileHeader.Characteristics);
  717.  
  718.     // Optional Header
  719.     OUTPUT("[+] OPTIONAL HEADER\n");
  720.     OUTPUT("\tMagic: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.Magic);
  721.     OUTPUT("\tAddressOfEntryPoint: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.AddressOfEntryPoint);
  722.     OUTPUT("\tImageBase: 0x%llX\n", analyzer.pNtHeaders64->OptionalHeader.ImageBase);
  723.     OUTPUT("\tSectionAlignment: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.SectionAlignment);
  724.     OUTPUT("\tFileAlignment: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.FileAlignment);
  725.     OUTPUT("\tSizeOfImage: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.SizeOfImage);
  726.     OUTPUT("\tSizeOfHeaders: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.SizeOfHeaders);
  727.     OUTPUT("\tSubsystem: 0x%X\n\n", analyzer.pNtHeaders64->OptionalHeader.Subsystem);
  728. }
  729. //}
  730.  
  731.         //russianheat (clipped peanalyzefile() code here)
  732.  
  733.  
  734.         // Data Directories analysis
  735. void AnalyzeDataDirectories(const PEAnalyzer& analyzer) {
  736.     OUTPUT("[+] DATA DIRECTORIES\n");
  737.     const IMAGE_DATA_DIRECTORY* dataDirectories = analyzer.is64Bit ?
  738.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory :
  739.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory;
  740.  
  741.     for (int i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++) {
  742.         if (dataDirectories[i].VirtualAddress != 0) {
  743.             OUTPUT("\t%s:\n", PEHelpers::GetDataDirectoryName(i).c_str());
  744.             OUTPUT("\t\tVirtualAddress: 0x%X\n", dataDirectories[i].VirtualAddress);
  745.             OUTPUT("\t\tSize: 0x%X\n", dataDirectories[i].Size);
  746.         }
  747.     }
  748.     OUTPUT("\n");
  749. }
  750.  
  751. // Safe memory check helper
  752. template<typename T>
  753. bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size) {
  754.     if (!ptr) return false;
  755.     DWORD_PTR start = reinterpret_cast<DWORD_PTR>(analyzer.lpFileContent);
  756.     DWORD_PTR end = start + analyzer.fileSize;
  757.     DWORD_PTR ptrAddr = reinterpret_cast<DWORD_PTR>(ptr);
  758.     return (ptrAddr >= start && (ptrAddr + size) <= end);
  759. }
  760.  
  761. // Section parsing with safety checks
  762. void ParseSections(const PEAnalyzer& analyzer) {
  763.     OUTPUT("[+] SECTION HEADERS\n");
  764.  
  765.     PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(
  766.         analyzer.is64Bit ?
  767.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  768.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32));
  769.  
  770.     WORD numberOfSections = analyzer.is64Bit ?
  771.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  772.         analyzer.pNtHeaders32->FileHeader.NumberOfSections;
  773.  
  774.     if (!IsSafeToRead(analyzer, pSection,
  775.         sizeof(IMAGE_SECTION_HEADER) * numberOfSections)) {
  776.         throw std::runtime_error("Invalid section headers");
  777.     }
  778.  
  779.     for (WORD i = 0; i < numberOfSections; i++, pSection++) {
  780.         char sectionName[IMAGE_SIZEOF_SHORT_NAME + 1] = {};
  781.         memcpy(sectionName, pSection->Name, IMAGE_SIZEOF_SHORT_NAME);
  782.  
  783.         // Sanitize section name
  784.         for (int j = 0; j < IMAGE_SIZEOF_SHORT_NAME; j++) {
  785.             if (!isprint(static_cast<unsigned char>(sectionName[j]))) {
  786.                 sectionName[j] = '\0';
  787.                 break;
  788.             }
  789.         }
  790.  
  791.         // Output section information
  792.         OUTPUT("\tSECTION: %s\n", sectionName);
  793.         OUTPUT("\t\tVirtualSize: 0x%X\n", pSection->Misc.VirtualSize);
  794.         OUTPUT("\t\tVirtualAddress: 0x%X\n", pSection->VirtualAddress);
  795.         OUTPUT("\t\tSizeOfRawData: 0x%X\n", pSection->SizeOfRawData);
  796.         OUTPUT("\t\tPointerToRawData: 0x%X\n", pSection->PointerToRawData);
  797.         OUTPUT("\t\tPointerToRelocations: 0x%X\n", pSection->PointerToRelocations);
  798.         OUTPUT("\t\tPointerToLinenumbers: 0x%X\n", pSection->PointerToLinenumbers);
  799.         OUTPUT("\t\tNumberOfRelocations: 0x%X\n", pSection->NumberOfRelocations);
  800.         OUTPUT("\t\tNumberOfLinenumbers: 0x%X\n", pSection->NumberOfLinenumbers);
  801.         OUTPUT("\t\tCharacteristics: 0x%X %s\n\n",
  802.             pSection->Characteristics,
  803.             PEHelpers::GetSectionProtection(pSection->Characteristics).c_str());
  804.     }
  805. } //end of parsesection here
  806.  
  807.     // Import Directory parsing with safety checks
  808. void ParseImportDirectory(const PEAnalyzer& analyzer) {
  809.     const auto& importDir = analyzer.is64Bit ?
  810.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] :
  811.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  812.  
  813.     if (!importDir.VirtualAddress || !importDir.Size) {
  814.         OUTPUT("\n[-] No import directory found.\n");
  815.         return;
  816.     }
  817.  
  818.     OUTPUT("\n[+] IMPORT DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  819.  
  820.     auto pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)PEHelpers::GetRvaPtr(
  821.         importDir.VirtualAddress,
  822.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  823.             (PIMAGE_NT_HEADERS)analyzer.pNtHeaders64 :
  824.             (PIMAGE_NT_HEADERS)analyzer.pNtHeaders32),
  825.         analyzer.is64Bit ?
  826.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  827.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  828.         analyzer.lpFileContent,
  829.         analyzer.fileSize);
  830.  
  831.     if (!IsSafeToRead(analyzer, pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  832.         throw std::runtime_error("Invalid import descriptor");
  833.     }
  834.  
  835.     while (pImportDesc->Name != 0) {
  836.         const char* dllName = (const char*)PEHelpers::GetRvaPtr(
  837.             pImportDesc->Name,
  838.             IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  839.                 reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  840.                 reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  841.             analyzer.is64Bit ?
  842.             analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  843.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  844.             analyzer.lpFileContent,
  845.             analyzer.fileSize);
  846.  
  847.         if (!IsSafeToRead(analyzer, dllName, 1)) {
  848.             break;
  849.         }
  850.  
  851.         OUTPUT("\n\tDLL NAME: %s\n", dllName);
  852.         OUTPUT("\tCharacteristics: 0x%X\n", pImportDesc->Characteristics);
  853.         OUTPUT("\tTimeDateStamp: 0x%X\n", pImportDesc->TimeDateStamp);
  854.         OUTPUT("\tForwarderChain: 0x%X\n", pImportDesc->ForwarderChain);
  855.         OUTPUT("\tFirstThunk: 0x%X\n\n", pImportDesc->FirstThunk);
  856.         OUTPUT("\tImported Functions:\n");
  857.  
  858.         // Parse functions based on architecture
  859.         if (analyzer.is64Bit) {
  860.             ParseImportFunctions64(analyzer, pImportDesc);
  861.         }
  862.         else {
  863.             ParseImportFunctions32(analyzer, pImportDesc);
  864.         }
  865.  
  866.         pImportDesc++;
  867.         if (!IsSafeToRead(analyzer, pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  868.             break;
  869.         }
  870.     }
  871. }
  872.  
  873. void ParseImportFunctions32(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc) {
  874.     auto pThunk = (PIMAGE_THUNK_DATA32)PEHelpers::GetRvaPtr(
  875.         pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  876.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  877.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  878.         analyzer.lpFileContent,
  879.         analyzer.fileSize);
  880.  
  881.     while (pThunk && pThunk->u1.AddressOfData) {
  882.         if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)) {
  883.             auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  884.                 pThunk->u1.AddressOfData,
  885.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  886.                 analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  887.                 analyzer.lpFileContent,
  888.                 analyzer.fileSize);
  889.  
  890.             if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  891.                 OUTPUT("\t\t%s\n", pImportByName->Name);
  892.             }
  893.         }
  894.         else {
  895.             OUTPUT("\t\tOrdinal: %d\n", pThunk->u1.Ordinal & 0xFFFF);
  896.         }
  897.         pThunk++;
  898.     }
  899. }
  900.  
  901. void ParseImportFunctions64(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc) {
  902.     auto pThunk = (PIMAGE_THUNK_DATA64)PEHelpers::GetRvaPtr(
  903.         pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  904.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  905.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  906.         analyzer.lpFileContent,
  907.         analyzer.fileSize);
  908.  
  909.     while (pThunk && pThunk->u1.AddressOfData) {
  910.         if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG64)) {
  911.             auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  912.                 (DWORD)pThunk->u1.AddressOfData,
  913.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  914.                 analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  915.                 analyzer.lpFileContent,
  916.                 analyzer.fileSize);
  917.  
  918.             if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  919.                 OUTPUT("\t\t%s\n", pImportByName->Name);
  920.             }
  921.         }
  922.         else {
  923.             OUTPUT("\t\tOrdinal: %lld\n", pThunk->u1.Ordinal & 0xFFFF);
  924.         }
  925.         pThunk++;
  926.     }
  927. }
  928.  
  929. // Export Directory parsing with safety checks
  930. void ParseExportDirectory(const PEAnalyzer& analyzer) {
  931.     const auto& exportDir = analyzer.is64Bit ?
  932.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] :
  933.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  934.  
  935.     if (!exportDir.VirtualAddress || !exportDir.Size) {
  936.         OUTPUT("\n[-] No export directory found.\n");
  937.         return;
  938.     }
  939.  
  940.     OUTPUT("\n[+] EXPORT DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  941.  
  942.     auto pExportDir = (PIMAGE_EXPORT_DIRECTORY)PEHelpers::GetRvaPtr(
  943.         exportDir.VirtualAddress,
  944.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  945.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  946.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  947.         analyzer.is64Bit ?
  948.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  949.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  950.         analyzer.lpFileContent,
  951.         analyzer.fileSize);
  952.  
  953.     if (!IsSafeToRead(analyzer, pExportDir, sizeof(IMAGE_EXPORT_DIRECTORY))) {
  954.         throw std::runtime_error("Invalid export directory");
  955.     }
  956.  
  957.     // Output export directory information
  958.     OUTPUT("\tCharacteristics: 0x%X\n", pExportDir->Characteristics);
  959.     OUTPUT("\tTimeDateStamp: 0x%X\n", pExportDir->TimeDateStamp);
  960.     OUTPUT("\tMajorVersion: %d\n", pExportDir->MajorVersion);
  961.     OUTPUT("\tMinorVersion: %d\n", pExportDir->MinorVersion);
  962.     OUTPUT("\tName: 0x%X\n", pExportDir->Name);
  963.     OUTPUT("\tBase: %d\n", pExportDir->Base);
  964.     OUTPUT("\tNumberOfFunctions: %d\n", pExportDir->NumberOfFunctions);
  965.     OUTPUT("\tNumberOfNames: %d\n", pExportDir->NumberOfNames);
  966.     OUTPUT("\tAddressOfFunctions: 0x%X\n", pExportDir->AddressOfFunctions);
  967.     OUTPUT("\tAddressOfNames: 0x%X\n", pExportDir->AddressOfNames);
  968.     OUTPUT("\tAddressOfNameOrdinals: 0x%X\n\n", pExportDir->AddressOfNameOrdinals);
  969.  
  970.     // Get export tables with safety checks
  971.  
  972.     // Add IMAGE_FIRST_SECTION and section count parameters
  973.     auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfFunctions,
  974.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  975.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  976.         analyzer.lpFileContent,
  977.         analyzer.fileSize);
  978.  
  979.     auto pNames = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNames,
  980.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  981.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  982.         analyzer.lpFileContent,
  983.         analyzer.fileSize);
  984.  
  985.     auto pOrdinals = (PWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNameOrdinals,
  986.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  987.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  988.         analyzer.lpFileContent,
  989.         analyzer.fileSize);
  990.  
  991.     //auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfFunctions, /*...*/);
  992.     //auto pNames = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNames, /*...*/);
  993.     //auto pOrdinals = (PWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNameOrdinals, /*...*/);
  994.  
  995.     if (!IsSafeToRead(analyzer, pFunctions, sizeof(DWORD) * pExportDir->NumberOfFunctions) ||
  996.         !IsSafeToRead(analyzer, pNames, sizeof(DWORD) * pExportDir->NumberOfNames) ||
  997.         !IsSafeToRead(analyzer, pOrdinals, sizeof(WORD) * pExportDir->NumberOfNames)) {
  998.         throw std::runtime_error("Invalid export tables");
  999.     }
  1000.  
  1001.     // Parse and output exported functions
  1002.     ParseExportedFunctions(analyzer, pExportDir, pFunctions, pNames, pOrdinals);
  1003. }
  1004.  
  1005. void ParseExportedFunctions(const PEAnalyzer& analyzer, PIMAGE_EXPORT_DIRECTORY pExportDir,
  1006.     PDWORD pFunctions, PDWORD pNames, PWORD pOrdinals) {
  1007.  
  1008.     OUTPUT("\tExported Functions:\n\n");
  1009.     for (DWORD i = 0; i < pExportDir->NumberOfNames; i++) {
  1010.         if (IsBadReadPtr(pNames + i, sizeof(DWORD)) ||
  1011.             IsBadReadPtr(pOrdinals + i, sizeof(WORD))) {
  1012.             break;
  1013.         }
  1014.  
  1015.         const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1016.             pNames[i],
  1017.             analyzer.is64Bit ? IMAGE_FIRST_SECTION((PIMAGE_NT_HEADERS64)analyzer.pNtHeaders64) : IMAGE_FIRST_SECTION((PIMAGE_NT_HEADERS32)analyzer.pNtHeaders32),
  1018.             analyzer.is64Bit ? analyzer.pNtHeaders64->FileHeader.NumberOfSections : analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1019.             analyzer.lpFileContent,
  1020.             analyzer.fileSize);
  1021.  
  1022.         /*const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1023.             pNames[i],
  1024.             IMAGE_FIRST_SECTION(analyzer.is64Bit ? analyzer.pNtHeaders64 : analyzer.pNtHeaders32),
  1025.             analyzer.is64Bit ? analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  1026.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1027.             analyzer.lpFileContent);*/
  1028.  
  1029.         if (functionName && !IsBadReadPtr(functionName, 1)) {
  1030.             WORD ordinal = pOrdinals[i];
  1031.             if (ordinal < pExportDir->NumberOfFunctions) {
  1032.                 DWORD functionRva = pFunctions[ordinal];
  1033.                 OUTPUT("\t\t%s (Ordinal: %d, RVA: 0x%08X)\n",
  1034.                     functionName,
  1035.                     ordinal + pExportDir->Base,
  1036.                     functionRva);
  1037.             }
  1038.         }
  1039.     }
  1040. }
  1041.  
  1042. void ParseResourceDirectory(const PEAnalyzer& analyzer) {
  1043.     const auto& resourceDir = analyzer.is64Bit ?
  1044.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE] :
  1045.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
  1046.  
  1047.     if (!resourceDir.VirtualAddress || !resourceDir.Size) {
  1048.         OUTPUT("\n[-] No resource directory found.\n");
  1049.         return;
  1050.     }
  1051.  
  1052.     OUTPUT("\n[+] RESOURCE DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  1053.  
  1054.     auto pResourceDir = (PIMAGE_RESOURCE_DIRECTORY)PEHelpers::GetRvaPtr(
  1055.         resourceDir.VirtualAddress,
  1056.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  1057.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  1058.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  1059.         analyzer.is64Bit ?
  1060.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  1061.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1062.         analyzer.lpFileContent,
  1063.         analyzer.fileSize);
  1064.  
  1065.     if (!IsSafeToRead(analyzer, pResourceDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1066.         throw std::runtime_error("Invalid resource directory");
  1067.     }
  1068.  
  1069.     ProcessResourceDirectory(pResourceDir, 0, nullptr, pResourceDir, analyzer);
  1070. }
  1071.  
  1072. void ProcessResourceDirectory(
  1073.     PIMAGE_RESOURCE_DIRECTORY resDir,
  1074.     int level,
  1075.     const wchar_t* type,
  1076.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1077.     const PEAnalyzer& analyzer)
  1078. {
  1079.     if (!IsSafeToRead(analyzer, resDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1080.         return;
  1081.     }
  1082.  
  1083.     auto entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resDir + 1);
  1084.     WORD totalEntries = resDir->NumberOfNamedEntries + resDir->NumberOfIdEntries;
  1085.  
  1086.     for (WORD i = 0; i < totalEntries; i++) {
  1087.         if (!IsSafeToRead(analyzer, entry + i, sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))) {
  1088.             break;
  1089.         }
  1090.  
  1091.         // Indent based on level
  1092.         for (int indent = 0; indent < level; indent++) {
  1093.             OUTPUT("\t");
  1094.         }
  1095.  
  1096.         // Process named entries
  1097.         if (entry[i].NameIsString) {
  1098.             ProcessNamedResourceEntry(entry[i], level, baseResourceDir, analyzer);
  1099.         }
  1100.         // Process ID entries
  1101.         else {
  1102.             ProcessIdResourceEntry(entry[i], level, type, baseResourceDir, analyzer);
  1103.         }
  1104.  
  1105.         // Process subdirectories or data
  1106.         if (entry[i].DataIsDirectory) {
  1107.             ProcessResourceSubdirectory(entry[i], level, type, baseResourceDir, analyzer);
  1108.         }
  1109.         else {
  1110.             ProcessResourceData(entry[i], level, type, baseResourceDir, analyzer);
  1111.         }
  1112.     }
  1113. }
  1114.  
  1115. //newlyfrom You,com Claude
  1116. void ProcessNamedResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1117.     int level, PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1118.     const PEAnalyzer& analyzer) {
  1119.  
  1120.     auto nameEntry = (PIMAGE_RESOURCE_DIR_STRING_U)((BYTE*)baseResourceDir + entry.NameOffset);
  1121.     if (!IsBadReadPtr(nameEntry, sizeof(IMAGE_RESOURCE_DIR_STRING_U))) {
  1122.         std::vector<wchar_t> resourceName(nameEntry->Length + 1);
  1123.         wcsncpy_s(resourceName.data(), nameEntry->Length + 1,
  1124.             nameEntry->NameString, nameEntry->Length);
  1125.         resourceName[nameEntry->Length] = L'\0';
  1126.  
  1127.         if (level == 0) {
  1128.             OUTPUT("Resource Type: Custom (%s)\n", resourceName.data());
  1129.         }
  1130.         else {
  1131.             OUTPUT("Name: %s\n", resourceName.data());
  1132.         }
  1133.     }
  1134. }
  1135.  
  1136. void ProcessIdResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1137.     int level, const wchar_t* type,
  1138.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1139.     const PEAnalyzer& analyzer) {
  1140.  
  1141.     if (level == 0) {
  1142.         DWORD resourceType = entry.Id;
  1143.         if (resourceType < 16) {
  1144.             OUTPUT("Resource Type: %s (ID: %d)\n", RESOURCE_TYPES[resourceType], resourceType);
  1145.         }
  1146.         else {
  1147.             OUTPUT("Resource Type: Custom (ID: %d)\n", resourceType);
  1148.         }
  1149.     }
  1150.     else {
  1151.         OUTPUT("ID: %d\n", entry.Id);
  1152.     }
  1153. }
  1154.  
  1155. void ProcessResourceSubdirectory(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1156.     int level, const wchar_t* type,
  1157.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1158.     const PEAnalyzer& analyzer) {
  1159.  
  1160.     auto nextDir = (PIMAGE_RESOURCE_DIRECTORY)((BYTE*)baseResourceDir + entry.OffsetToDirectory);
  1161.     if (!IsBadReadPtr(nextDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1162.         ProcessResourceDirectory(nextDir, level + 1,
  1163.             level == 0 ? RESOURCE_TYPES[min(entry.Id, 15)] : type,
  1164.             baseResourceDir, analyzer);
  1165.     }
  1166. }
  1167.  
  1168. void ProcessResourceData(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1169.     int level, const wchar_t* type,
  1170.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1171.     const PEAnalyzer& analyzer) {
  1172.  
  1173.     auto dataEntry = (PIMAGE_RESOURCE_DATA_ENTRY)((BYTE*)baseResourceDir + entry.OffsetToData);
  1174.     if (!IsBadReadPtr(dataEntry, sizeof(IMAGE_RESOURCE_DATA_ENTRY))) {
  1175.         for (int indent = 0; indent < level + 1; indent++) {
  1176.             OUTPUT("\t");
  1177.         }
  1178.         OUTPUT("Size: %d bytes, RVA: 0x%X\n", dataEntry->Size, dataEntry->OffsetToData);
  1179.     }
  1180. }
  1181.  
  1182. void ParseDebugDirectory(const PEAnalyzer& analyzer) {
  1183.     const auto& debugDir = analyzer.is64Bit ?
  1184.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG] :
  1185.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
  1186.  
  1187.     if (!debugDir.VirtualAddress || !debugDir.Size) {
  1188.         OUTPUT("\n[-] No debug directory found.\n");
  1189.         return;
  1190.     }
  1191.  
  1192.     OUTPUT("\n[+] DEBUG DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  1193.  
  1194.     auto pDebugDir = (PIMAGE_DEBUG_DIRECTORY)PEHelpers::GetRvaPtr(
  1195.         debugDir.VirtualAddress,
  1196.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  1197.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  1198.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  1199.         analyzer.is64Bit ?
  1200.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  1201.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1202.         analyzer.lpFileContent,
  1203.         analyzer.fileSize);
  1204.  
  1205.     if (!IsSafeToRead(analyzer, pDebugDir, sizeof(IMAGE_DEBUG_DIRECTORY))) {
  1206.         throw std::runtime_error("Invalid debug directory");
  1207.     }
  1208.  
  1209.     DWORD numEntries = min(debugDir.Size / sizeof(IMAGE_DEBUG_DIRECTORY), 16);
  1210.     for (DWORD i = 0; i < numEntries; i++) {
  1211.         ProcessDebugEntry(pDebugDir[i], analyzer);
  1212.     }
  1213. }
  1214.  
  1215. void ProcessDebugEntry(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer) {
  1216.     OUTPUT("\tDebug Entry:\n");
  1217.     OUTPUT("\tCharacteristics: 0x%X\n", debugEntry.Characteristics);
  1218.     OUTPUT("\tTimeDateStamp: 0x%X\n", debugEntry.TimeDateStamp);
  1219.     OUTPUT("\tVersion: %d.%d\n", debugEntry.MajorVersion, debugEntry.MinorVersion);
  1220.     OUTPUT("\tType: 0x%X", debugEntry.Type);
  1221.  
  1222.     // Output debug type
  1223.     switch (debugEntry.Type) {
  1224.     case IMAGE_DEBUG_TYPE_COFF:
  1225.         OUTPUT(" (COFF)\n"); break;
  1226.     case IMAGE_DEBUG_TYPE_CODEVIEW:
  1227.         OUTPUT(" (CodeView)\n");
  1228.         ProcessCodeViewDebugInfo(debugEntry, analyzer);
  1229.         break;
  1230.         // ... other debug types ...
  1231.     default:
  1232.         OUTPUT(" (Unknown)\n"); break;
  1233.     }
  1234.  
  1235.     OUTPUT("\tSizeOfData: 0x%X\n", debugEntry.SizeOfData);
  1236.     OUTPUT("\tAddressOfRawData: 0x%X\n", debugEntry.AddressOfRawData);
  1237.     OUTPUT("\tPointerToRawData: 0x%X\n\n", debugEntry.PointerToRawData);
  1238. }
  1239.  
  1240. // Helper functions for processing specific debug info types
  1241. void ProcessCodeViewDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer) {
  1242.     if (debugEntry.Type != IMAGE_DEBUG_TYPE_CODEVIEW ||
  1243.         !debugEntry.PointerToRawData ||
  1244.         debugEntry.SizeOfData < sizeof(DWORD)) {
  1245.         return;
  1246.     }
  1247.  
  1248.     auto pCVHeader = (DWORD*)((BYTE*)analyzer.lpFileContent + debugEntry.PointerToRawData);
  1249.     if (!IsSafeToRead(analyzer, pCVHeader, sizeof(DWORD))) {
  1250.         return;
  1251.     }
  1252.  
  1253.     // Process different CodeView formats
  1254.     switch (*pCVHeader) {
  1255.     case 0x53445352: // 'RSDS'
  1256.         ProcessRSDSDebugInfo(debugEntry, pCVHeader, analyzer);
  1257.         break;
  1258.     case 0x3031424E: // 'NB10'
  1259.         ProcessNB10DebugInfo(debugEntry, pCVHeader, analyzer);
  1260.         break;
  1261.     }
  1262. }
  1263.  
  1264. void ProcessRSDSDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  1265.     const PEAnalyzer& analyzer) {
  1266.  
  1267.     if (debugEntry.SizeOfData >= (sizeof(DWORD) + sizeof(GUID) + sizeof(DWORD) + 1)) {
  1268.         auto pCVData = (char*)(pCVHeader + 1);
  1269.         if (!IsBadReadPtr(pCVData + 16, 1)) {
  1270.             auto guid = (GUID*)pCVData;
  1271.             DWORD age = *(DWORD*)(pCVData + 16);
  1272.             const char* pdbPath = pCVData + 20;
  1273.  
  1274.             OUTPUT("\tPDB Information:\n");
  1275.             OUTPUT("\tGUID: {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
  1276.                 guid->Data1, guid->Data2, guid->Data3,
  1277.                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  1278.                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  1279.             OUTPUT("\tAge: %d\n", age);
  1280.             OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  1281.         }
  1282.     }
  1283. }
  1284.  
  1285. void ProcessNB10DebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  1286.     const PEAnalyzer& analyzer) {
  1287.  
  1288.     if (debugEntry.SizeOfData >= 16) {
  1289.         auto pNB10Data = (char*)(pCVHeader + 1);
  1290.         DWORD offset = *(DWORD*)pNB10Data;
  1291.         DWORD timestamp = *(DWORD*)(pNB10Data + 4);
  1292.         DWORD age = *(DWORD*)(pNB10Data + 8);
  1293.         const char* pdbPath = pNB10Data + 12;
  1294.  
  1295.         OUTPUT("\tPDB Information (NB10):\n");
  1296.         OUTPUT("\tOffset: 0x%X\n", offset);
  1297.         OUTPUT("\tTimestamp: 0x%X\n", timestamp);
  1298.         OUTPUT("\tAge: %d\n", age);
  1299.         OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  1300.     }
  1301. }
  1302.  
  1303. //colonelburton
  1304.  
  1305. void ParseImportDirectory32(const PEAnalyzer& analyzer) {
  1306.     const auto& importDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  1307.     if (!importDir.VirtualAddress || !importDir.Size) return;
  1308.  
  1309.     if (!PEHelpers::IsRvaValid(importDir.VirtualAddress, analyzer.fileSize,
  1310.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1311.         OUTPUT("[-] Invalid import directory RVA!\n");
  1312.         throw std::runtime_error("RVA out of bounds");
  1313.         return;
  1314.     }
  1315.  
  1316.     OUTPUT("\n[+] IMPORT DIRECTORY (32-bit)\n");
  1317.     auto pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)PEHelpers::GetRvaPtr(
  1318.         importDir.VirtualAddress,
  1319.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1320.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1321.         analyzer.lpFileContent,
  1322.         analyzer.fileSize);
  1323.  
  1324.     if (!pImportDesc) return;
  1325.  
  1326.     while (pImportDesc->Name != 0) {
  1327.         if (IsBadReadPtr(pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  1328.             OUTPUT("[-] Invalid import descriptor detected!\n");
  1329.             break;
  1330.         }
  1331.  
  1332.         const char* dllName = (const char*)PEHelpers::GetRvaPtr(
  1333.             pImportDesc->Name,
  1334.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1335.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1336.             analyzer.lpFileContent,
  1337.             analyzer.fileSize);
  1338.  
  1339.         if (dllName && !IsBadReadPtr(dllName, 1)) {
  1340.             std::vector<wchar_t> wideDllName(MAX_PATH);
  1341.             MultiByteToWideChar(CP_ACP, 0, dllName, -1, wideDllName.data(), MAX_PATH);
  1342.  
  1343.             OUTPUT("\n\tDLL NAME: %s\n", wideDllName.data());
  1344.             OUTPUT("\tCharacteristics: 0x%X\n", pImportDesc->Characteristics);
  1345.             OUTPUT("\tTimeDateStamp: 0x%X\n", pImportDesc->TimeDateStamp);
  1346.             OUTPUT("\tForwarderChain: 0x%X\n", pImportDesc->ForwarderChain);
  1347.             OUTPUT("\tFirstThunk: 0x%X\n", pImportDesc->FirstThunk);
  1348.             OUTPUT("\n\tImported Functions:\n");
  1349.  
  1350.             auto pThunk = (PIMAGE_THUNK_DATA32)PEHelpers::GetRvaPtr(
  1351.                 pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  1352.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1353.                 analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1354.                 analyzer.lpFileContent,
  1355.                 analyzer.fileSize);
  1356.  
  1357.             while (pThunk && pThunk->u1.AddressOfData) {
  1358.                 if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)) {
  1359.                     auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  1360.                         pThunk->u1.AddressOfData,
  1361.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1362.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1363.                         analyzer.lpFileContent,
  1364.                         analyzer.fileSize);
  1365.  
  1366.                     if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  1367.                         std::vector<wchar_t> wideFuncName(MAX_PATH);
  1368.                         MultiByteToWideChar(CP_ACP, 0, (char*)pImportByName->Name, -1,
  1369.                             wideFuncName.data(), MAX_PATH);
  1370.                         OUTPUT("\t\t%s\n", wideFuncName.data());
  1371.                     }
  1372.                 }
  1373.                 else {
  1374.                     OUTPUT("\t\tOrdinal: %d\n", pThunk->u1.Ordinal & 0xFFFF);
  1375.                 }
  1376.                 pThunk++;
  1377.             }
  1378.         }
  1379.         pImportDesc++;
  1380.     }
  1381. }
  1382.  
  1383. void ParseImportDirectory64(const PEAnalyzer& analyzer) {
  1384.     const auto& importDir = analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  1385.     if (!importDir.VirtualAddress || !importDir.Size) return;
  1386.  
  1387.     if (!PEHelpers::IsRvaValid(importDir.VirtualAddress, analyzer.fileSize,
  1388.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64))) {
  1389.         OUTPUT("[-] Invalid import directory RVA!\n");
  1390.         throw std::runtime_error("RVA out of bounds");
  1391.         return;
  1392.     }
  1393.  
  1394.     OUTPUT("\n[+] IMPORT DIRECTORY (64-bit)\n");
  1395.     auto pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)PEHelpers::GetRvaPtr(
  1396.         importDir.VirtualAddress,
  1397.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1398.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1399.         analyzer.lpFileContent,
  1400.         analyzer.fileSize);
  1401.  
  1402.     if (!pImportDesc) return;
  1403.  
  1404.     while (pImportDesc->Name != 0) {
  1405.         if (IsBadReadPtr(pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  1406.             OUTPUT("[-] Invalid import descriptor detected!\n");
  1407.             break;
  1408.         }
  1409.  
  1410.         const char* dllName = (const char*)PEHelpers::GetRvaPtr(
  1411.             pImportDesc->Name,
  1412.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1413.             analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1414.             analyzer.lpFileContent,
  1415.             analyzer.fileSize);
  1416.  
  1417.         if (dllName && !IsBadReadPtr(dllName, 1)) {
  1418.             std::vector<wchar_t> wideDllName(MAX_PATH);
  1419.             MultiByteToWideChar(CP_ACP, 0, dllName, -1, wideDllName.data(), MAX_PATH);
  1420.  
  1421.             OUTPUT("\n\tDLL NAME: %s\n", wideDllName.data());
  1422.             OUTPUT("\tCharacteristics: 0x%X\n", pImportDesc->Characteristics);
  1423.             OUTPUT("\tTimeDateStamp: 0x%X\n", pImportDesc->TimeDateStamp);
  1424.             OUTPUT("\tForwarderChain: 0x%X\n", pImportDesc->ForwarderChain);
  1425.             OUTPUT("\tFirstThunk: 0x%X\n", pImportDesc->FirstThunk);
  1426.             OUTPUT("\n\tImported Functions:\n");
  1427.  
  1428.             auto pThunk = (PIMAGE_THUNK_DATA64)PEHelpers::GetRvaPtr(
  1429.                 pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  1430.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1431.                 analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1432.                 analyzer.lpFileContent,
  1433.                 analyzer.fileSize);
  1434.  
  1435.             while (pThunk && pThunk->u1.AddressOfData) {
  1436.                 if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG64)) {
  1437.                     auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  1438.                         (DWORD)pThunk->u1.AddressOfData,
  1439.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1440.                         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1441.                         analyzer.lpFileContent,
  1442.                         analyzer.fileSize);
  1443.  
  1444.                     if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  1445.                         std::vector<wchar_t> wideFuncName(MAX_PATH);
  1446.                         MultiByteToWideChar(CP_ACP, 0, (char*)pImportByName->Name, -1,
  1447.                             wideFuncName.data(), MAX_PATH);
  1448.                         OUTPUT("\t\t%s\n", wideFuncName.data());
  1449.                     }
  1450.                 }
  1451.                 else {
  1452.                     OUTPUT("\t\tOrdinal: %lld\n", pThunk->u1.Ordinal & 0xFFFF);
  1453.                 }
  1454.                 pThunk++;
  1455.             }
  1456.         }
  1457.         pImportDesc++;
  1458.     }
  1459. }
  1460.  
  1461. /*void ParseImportDirectory(const PEAnalyzer& analyzer) {
  1462.     if (analyzer.is64Bit) {
  1463.         ParseImportDirectory64(analyzer);
  1464.     }
  1465.     else {
  1466.         ParseImportDirectory32(analyzer);
  1467.     }
  1468. }*/ //removing the empty content duplicates
  1469. //}
  1470.  
  1471. void ParseExportDirectory32(const PEAnalyzer& analyzer) {
  1472.     const auto& exportDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  1473.     if (!exportDir.VirtualAddress || !exportDir.Size) return;
  1474.  
  1475.     if (!PEHelpers::IsRvaValid(exportDir.VirtualAddress, analyzer.fileSize,
  1476.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1477.         OUTPUT("[-] Invalid export directory RVA!\n");
  1478.         throw std::runtime_error("RVA out of bounds");
  1479.         return;
  1480.     }
  1481.  
  1482.     OUTPUT("\n[+] EXPORT DIRECTORY (32-bit)\n");
  1483.     auto pExportDir = (PIMAGE_EXPORT_DIRECTORY)PEHelpers::GetRvaPtr(
  1484.         exportDir.VirtualAddress,
  1485.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1486.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1487.         analyzer.lpFileContent,
  1488.         analyzer.fileSize);
  1489.  
  1490.     if (!pExportDir || IsBadReadPtr(pExportDir, sizeof(IMAGE_EXPORT_DIRECTORY))) {
  1491.         OUTPUT("[-] Invalid export directory structure!\n");
  1492.         return;
  1493.     }
  1494.  
  1495.     OUTPUT("\tCharacteristics: 0x%X\n", pExportDir->Characteristics);
  1496.     OUTPUT("\tTimeDateStamp: 0x%X\n", pExportDir->TimeDateStamp);
  1497.     OUTPUT("\tMajorVersion: %d\n", pExportDir->MajorVersion);
  1498.     OUTPUT("\tMinorVersion: %d\n", pExportDir->MinorVersion);
  1499.     OUTPUT("\tName: 0x%X\n", pExportDir->Name);
  1500.     OUTPUT("\tBase: %d\n", pExportDir->Base);
  1501.     OUTPUT("\tNumberOfFunctions: %d\n", pExportDir->NumberOfFunctions);
  1502.     OUTPUT("\tNumberOfNames: %d\n", pExportDir->NumberOfNames);
  1503.     OUTPUT("\tAddressOfFunctions: 0x%X\n", pExportDir->AddressOfFunctions);
  1504.     OUTPUT("\tAddressOfNames: 0x%X\n", pExportDir->AddressOfNames);
  1505.     OUTPUT("\tAddressOfNameOrdinals: 0x%X\n\n", pExportDir->AddressOfNameOrdinals);
  1506.  
  1507.     auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(
  1508.         pExportDir->AddressOfFunctions,
  1509.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1510.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1511.         analyzer.lpFileContent,
  1512.         analyzer.fileSize);
  1513.  
  1514.     auto pNames = (PDWORD)PEHelpers::GetRvaPtr(
  1515.         pExportDir->AddressOfNames,
  1516.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1517.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1518.         analyzer.lpFileContent,
  1519.         analyzer.fileSize);
  1520.  
  1521.     auto pNameOrdinals = (PWORD)PEHelpers::GetRvaPtr(
  1522.         pExportDir->AddressOfNameOrdinals,
  1523.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1524.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1525.         analyzer.lpFileContent,
  1526.         analyzer.fileSize);
  1527.  
  1528.     if (!pNames || !pNameOrdinals || !pFunctions) {
  1529.         OUTPUT("[-] Invalid export address tables!\n");
  1530.         return;
  1531.     }
  1532.  
  1533.     OUTPUT("\tExported Functions:\n\n");
  1534.     for (DWORD i = 0; i < pExportDir->NumberOfNames; i++) {
  1535.         if (IsBadReadPtr(pNames + i, sizeof(DWORD)) ||
  1536.             IsBadReadPtr(pNameOrdinals + i, sizeof(WORD))) {
  1537.             break;
  1538.         }
  1539.  
  1540.         const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1541.             pNames[i],
  1542.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1543.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1544.             analyzer.lpFileContent,
  1545.             analyzer.fileSize);
  1546.  
  1547.         if (functionName && !IsBadReadPtr(functionName, 1)) {
  1548.             WORD ordinal = pNameOrdinals[i];
  1549.             if (ordinal < pExportDir->NumberOfFunctions) {
  1550.                 DWORD functionRva = pFunctions[ordinal];
  1551.  
  1552.                 // Check for forwarded export
  1553.                 if (functionRva >= exportDir.VirtualAddress &&
  1554.                     functionRva < (exportDir.VirtualAddress + exportDir.Size)) {
  1555.  
  1556.                     const char* forwardName = (const char*)PEHelpers::GetRvaPtr(
  1557.                         functionRva,
  1558.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1559.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1560.                         analyzer.lpFileContent,
  1561.                         analyzer.fileSize);
  1562.  
  1563.                     if (forwardName && !IsBadReadPtr(forwardName, 1)) {
  1564.                         std::vector<wchar_t> wideForwardName(MAX_PATH);
  1565.                         MultiByteToWideChar(CP_ACP, 0, forwardName, -1,
  1566.                             wideForwardName.data(), MAX_PATH);
  1567.                         OUTPUT("\t\t%s (Ordinal: %d) -> Forward to: %s\n",
  1568.                             functionName,
  1569.                             ordinal + pExportDir->Base,
  1570.                             wideForwardName.data());
  1571.                     }
  1572.                 }
  1573.                 else {
  1574.                     OUTPUT("\t\t%s (Ordinal: %d, RVA: 0x%08X)\n",
  1575.                         functionName,
  1576.                         ordinal + pExportDir->Base,
  1577.                         functionRva);
  1578.                 }
  1579.             }
  1580.         }
  1581.     }
  1582. }
  1583.  
  1584. void ParseExportDirectory64(const PEAnalyzer& analyzer) {
  1585.     const auto& exportDir = analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  1586.     if (!exportDir.VirtualAddress || !exportDir.Size) return;
  1587.  
  1588.     if (!PEHelpers::IsRvaValid(exportDir.VirtualAddress, analyzer.fileSize,
  1589.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64))) {
  1590.         OUTPUT("[-] Invalid export directory RVA!\n");
  1591.         throw std::runtime_error("RVA out of bounds");
  1592.         return;
  1593.     }
  1594.  
  1595.     OUTPUT("\n[+] EXPORT DIRECTORY (64-bit)\n");
  1596.     // Rest of the implementation is identical to 32-bit version
  1597.     // Just using pNtHeaders64 instead of pNtHeaders64
  1598.     auto pExportDir = (PIMAGE_EXPORT_DIRECTORY)PEHelpers::GetRvaPtr(
  1599.         exportDir.VirtualAddress,
  1600.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1601.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1602.         analyzer.lpFileContent,
  1603.         analyzer.fileSize);
  1604.  
  1605.     if (!pExportDir || IsBadReadPtr(pExportDir, sizeof(IMAGE_EXPORT_DIRECTORY))) {
  1606.         OUTPUT("[-] Invalid export directory structure!\n");
  1607.         return;
  1608.     }
  1609.  
  1610.     OUTPUT("\tCharacteristics: 0x%X\n", pExportDir->Characteristics);
  1611.     OUTPUT("\tTimeDateStamp: 0x%X\n", pExportDir->TimeDateStamp);
  1612.     OUTPUT("\tMajorVersion: %d\n", pExportDir->MajorVersion);
  1613.     OUTPUT("\tMinorVersion: %d\n", pExportDir->MinorVersion);
  1614.     OUTPUT("\tName: 0x%X\n", pExportDir->Name);
  1615.     OUTPUT("\tBase: %d\n", pExportDir->Base);
  1616.     OUTPUT("\tNumberOfFunctions: %d\n", pExportDir->NumberOfFunctions);
  1617.     OUTPUT("\tNumberOfNames: %d\n", pExportDir->NumberOfNames);
  1618.     OUTPUT("\tAddressOfFunctions: 0x%X\n", pExportDir->AddressOfFunctions);
  1619.     OUTPUT("\tAddressOfNames: 0x%X\n", pExportDir->AddressOfNames);
  1620.     OUTPUT("\tAddressOfNameOrdinals: 0x%X\n\n", pExportDir->AddressOfNameOrdinals);
  1621.  
  1622.     auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(
  1623.         pExportDir->AddressOfFunctions,
  1624.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1625.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1626.         analyzer.lpFileContent,
  1627.         analyzer.fileSize);
  1628.  
  1629.     auto pNames = (PDWORD)PEHelpers::GetRvaPtr(
  1630.         pExportDir->AddressOfNames,
  1631.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1632.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1633.         analyzer.lpFileContent,
  1634.         analyzer.fileSize);
  1635.  
  1636.     auto pNameOrdinals = (PWORD)PEHelpers::GetRvaPtr(
  1637.         pExportDir->AddressOfNameOrdinals,
  1638.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1639.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1640.         analyzer.lpFileContent,
  1641.         analyzer.fileSize);
  1642.  
  1643.     if (!pNames || !pNameOrdinals || !pFunctions) {
  1644.         OUTPUT("[-] Invalid export address tables!\n");
  1645.         return;
  1646.     }
  1647.  
  1648.     OUTPUT("\tExported Functions:\n\n");
  1649.     for (DWORD i = 0; i < pExportDir->NumberOfNames; i++) {
  1650.         if (IsBadReadPtr(pNames + i, sizeof(DWORD)) ||
  1651.             IsBadReadPtr(pNameOrdinals + i, sizeof(WORD))) {
  1652.             break;
  1653.         }
  1654.  
  1655.         const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1656.             pNames[i],
  1657.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1658.             analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1659.             analyzer.lpFileContent,
  1660.             analyzer.fileSize);
  1661.  
  1662.         if (functionName && !IsBadReadPtr(functionName, 1)) {
  1663.             WORD ordinal = pNameOrdinals[i];
  1664.             if (ordinal < pExportDir->NumberOfFunctions) {
  1665.                 DWORD functionRva = pFunctions[ordinal];
  1666.  
  1667.                 // Check for forwarded export
  1668.                 if (functionRva >= exportDir.VirtualAddress &&
  1669.                     functionRva < (exportDir.VirtualAddress + exportDir.Size)) {
  1670.  
  1671.                     const char* forwardName = (const char*)PEHelpers::GetRvaPtr(
  1672.                         functionRva,
  1673.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1674.                         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1675.                         analyzer.lpFileContent,
  1676.                         analyzer.fileSize);
  1677.  
  1678.                     if (forwardName && !IsBadReadPtr(forwardName, 1)) {
  1679.                         std::vector<wchar_t> wideForwardName(MAX_PATH);
  1680.                         MultiByteToWideChar(CP_ACP, 0, forwardName, -1,
  1681.                             wideForwardName.data(), MAX_PATH);
  1682.                         OUTPUT("\t\t%s (Ordinal: %d) -> Forward to: %s\n",
  1683.                             functionName,
  1684.                             ordinal + pExportDir->Base,
  1685.                             wideForwardName.data());
  1686.                     }
  1687.                 }
  1688.                 else {
  1689.                     OUTPUT("\t\t%s (Ordinal: %d, RVA: 0x%08X)\n",
  1690.                         functionName,
  1691.                         ordinal + pExportDir->Base,
  1692.                         functionRva);
  1693.                 }
  1694.             }
  1695.         }
  1696.     }
  1697. }
  1698. // Copying the same logic as ParseExportDirectory32 but with 64-bit headers
  1699. // ... [Same implementation as above, just using pNtHeaders64]
  1700.  
  1701. /*void ParseExportDirectory(const PEAnalyzer& analyzer) {
  1702.     if (analyzer.is64Bit) {
  1703.         ParseExportDirectory64(analyzer);
  1704.     }
  1705.     else {
  1706.         ParseExportDirectory32(analyzer);
  1707.     }
  1708. }*/ //removing this duplicate
  1709.  
  1710. void ProcessResourceDirectory32(
  1711.     PIMAGE_RESOURCE_DIRECTORY resDir,
  1712.     int level,
  1713.     const wchar_t* type,
  1714.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1715.     const wchar_t* resourceTypes[],
  1716.     const PEAnalyzer& analyzer)
  1717. {
  1718.     if (IsBadReadPtr(resDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1719.         return;
  1720.     }
  1721.  
  1722.     auto entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resDir + 1);
  1723.     WORD totalEntries = resDir->NumberOfNamedEntries + resDir->NumberOfIdEntries;
  1724.  
  1725.     for (WORD i = 0; i < totalEntries; i++) {
  1726.         if (IsBadReadPtr(entry + i, sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))) {
  1727.             break;
  1728.         }
  1729.  
  1730.         for (int indent = 0; indent < level; indent++) {
  1731.             OUTPUT("\t");
  1732.         }
  1733.  
  1734.         if (entry[i].NameIsString) {
  1735.             auto nameEntry = (PIMAGE_RESOURCE_DIR_STRING_U)((BYTE*)baseResourceDir + entry[i].NameOffset);
  1736.             if (!IsBadReadPtr(nameEntry, sizeof(IMAGE_RESOURCE_DIR_STRING_U))) {
  1737.                 std::vector<wchar_t> resourceName(nameEntry->Length + 1);
  1738.                 wcsncpy_s(resourceName.data(), nameEntry->Length + 1,
  1739.                     nameEntry->NameString, nameEntry->Length);
  1740.                 resourceName[nameEntry->Length] = L'\0';
  1741.  
  1742.                 if (level == 0) {
  1743.                     OUTPUT("Resource Type: Custom (%s)\n", resourceName.data());
  1744.                 }
  1745.                 else {
  1746.                     OUTPUT("Name: %s\n", resourceName.data());
  1747.                 }
  1748.             }
  1749.         }
  1750.         else {
  1751.             if (level == 0) {
  1752.                 DWORD resourceType = entry[i].Id;
  1753.                 if (resourceType < 16) {
  1754.                     OUTPUT("Resource Type: %s (ID: %d)\n", resourceTypes[resourceType], resourceType);
  1755.                 }
  1756.                 else {
  1757.                     OUTPUT("Resource Type: Custom (ID: %d)\n", resourceType);
  1758.                 }
  1759.             }
  1760.             else {
  1761.                 OUTPUT("ID: %d\n", entry[i].Id);
  1762.             }
  1763.         }
  1764.  
  1765.         if (entry[i].DataIsDirectory) {
  1766.             auto nextDir = (PIMAGE_RESOURCE_DIRECTORY)((BYTE*)baseResourceDir + entry[i].OffsetToDirectory);
  1767.             if (!IsBadReadPtr(nextDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1768.                 ProcessResourceDirectory32(nextDir, level + 1,
  1769.                     level == 0 ? resourceTypes[min(entry[i].Id, 15)] : type,
  1770.                     baseResourceDir, resourceTypes, analyzer);
  1771.             }
  1772.         }
  1773.         else {
  1774.             auto dataEntry = (PIMAGE_RESOURCE_DATA_ENTRY)((BYTE*)baseResourceDir + entry[i].OffsetToData);
  1775.             if (!IsBadReadPtr(dataEntry, sizeof(IMAGE_RESOURCE_DATA_ENTRY))) {
  1776.                 for (int indent = 0; indent < level + 1; indent++) {
  1777.                     OUTPUT("\t");
  1778.                 }
  1779.                 OUTPUT("Size: %d bytes, RVA: 0x%X\n", dataEntry->Size, dataEntry->OffsetToData);
  1780.  
  1781.                 // Special handling for Version resources
  1782.                 if (type && wcscmp(type, L"Version") == 0) {
  1783.                     auto versionData = (BYTE*)PEHelpers::GetRvaPtr(
  1784.                         dataEntry->OffsetToData,
  1785.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1786.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1787.                         analyzer.lpFileContent,
  1788.                         analyzer.fileSize);
  1789.  
  1790.                     if (versionData && !IsBadReadPtr(versionData, sizeof(VS_FIXEDFILEINFO))) {
  1791.                         auto versionInfo = (VS_FIXEDFILEINFO*)(versionData + 40);
  1792.                         if (versionInfo->dwSignature == 0xFEEF04BD) {
  1793.                             for (int indent = 0; indent < level + 2; indent++) {
  1794.                                 OUTPUT("\t");
  1795.                             }
  1796.                             OUTPUT("File Version: %d.%d.%d.%d\n",
  1797.                                 HIWORD(versionInfo->dwFileVersionMS),
  1798.                                 LOWORD(versionInfo->dwFileVersionMS),
  1799.                                 HIWORD(versionInfo->dwFileVersionLS),
  1800.                                 LOWORD(versionInfo->dwFileVersionLS));
  1801.                         }
  1802.                     }
  1803.                 }
  1804.             }
  1805.         }
  1806.     }
  1807. }
  1808.  
  1809. void ProcessResourceDirectory64(
  1810.     PIMAGE_RESOURCE_DIRECTORY resDir,
  1811.     int level,
  1812.     const wchar_t* type,
  1813.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1814.     const wchar_t* resourceTypes[],
  1815.     const PEAnalyzer& analyzer)
  1816. {
  1817.     // Similar to ProcessResourceDirectory32 but using 64-bit structures
  1818.     // Main difference is using analyzer.pNtHeaders64 instead of analyzer.pNtHeaders32
  1819.     if (IsBadReadPtr(resDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1820.         return;
  1821.         // Rest of the implementation follows the same pattern
  1822.     }
  1823.  
  1824.     auto entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resDir + 1);
  1825.     WORD totalEntries = resDir->NumberOfNamedEntries + resDir->NumberOfIdEntries;
  1826.  
  1827.     for (WORD i = 0; i < totalEntries; i++) {
  1828.         if (IsBadReadPtr(entry + i, sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))) {
  1829.             break;
  1830.         }
  1831.  
  1832.         for (int indent = 0; indent < level; indent++) {
  1833.             OUTPUT("\t");
  1834.         }
  1835.  
  1836.         if (entry[i].NameIsString) {
  1837.             auto nameEntry = (PIMAGE_RESOURCE_DIR_STRING_U)((BYTE*)baseResourceDir + entry[i].NameOffset);
  1838.             if (!IsBadReadPtr(nameEntry, sizeof(IMAGE_RESOURCE_DIR_STRING_U))) {
  1839.                 std::vector<wchar_t> resourceName(nameEntry->Length + 1);
  1840.                 wcsncpy_s(resourceName.data(), nameEntry->Length + 1,
  1841.                     nameEntry->NameString, nameEntry->Length);
  1842.                 resourceName[nameEntry->Length] = L'\0';
  1843.  
  1844.                 if (level == 0) {
  1845.                     OUTPUT("Resource Type: Custom (%s)\n", resourceName.data());
  1846.                 }
  1847.                 else {
  1848.                     OUTPUT("Name: %s\n", resourceName.data());
  1849.                 }
  1850.             }
  1851.         }
  1852.         else {
  1853.             if (level == 0) {
  1854.                 DWORD resourceType = entry[i].Id;
  1855.                 if (resourceType < 16) {
  1856.                     OUTPUT("Resource Type: %s (ID: %d)\n", resourceTypes[resourceType], resourceType);
  1857.                 }
  1858.                 else {
  1859.                     OUTPUT("Resource Type: Custom (ID: %d)\n", resourceType);
  1860.                 }
  1861.             }
  1862.             else {
  1863.                 OUTPUT("ID: %d\n", entry[i].Id);
  1864.             }
  1865.         }
  1866.  
  1867.         if (entry[i].DataIsDirectory) {
  1868.             auto nextDir = (PIMAGE_RESOURCE_DIRECTORY)((BYTE*)baseResourceDir + entry[i].OffsetToDirectory);
  1869.             if (!IsBadReadPtr(nextDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1870.                 ProcessResourceDirectory32(nextDir, level + 1,
  1871.                     level == 0 ? resourceTypes[min(entry[i].Id, 15)] : type,
  1872.                     baseResourceDir, resourceTypes, analyzer);
  1873.             }
  1874.         }
  1875.         else {
  1876.             auto dataEntry = (PIMAGE_RESOURCE_DATA_ENTRY)((BYTE*)baseResourceDir + entry[i].OffsetToData);
  1877.             if (!IsBadReadPtr(dataEntry, sizeof(IMAGE_RESOURCE_DATA_ENTRY))) {
  1878.                 for (int indent = 0; indent < level + 1; indent++) {
  1879.                     OUTPUT("\t");
  1880.                 }
  1881.                 OUTPUT("Size: %d bytes, RVA: 0x%X\n", dataEntry->Size, dataEntry->OffsetToData);
  1882.  
  1883.                 // Special handling for Version resources
  1884.                 if (type && wcscmp(type, L"Version") == 0) {
  1885.                     auto versionData = (BYTE*)PEHelpers::GetRvaPtr(
  1886.                         dataEntry->OffsetToData,
  1887.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1888.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1889.                         analyzer.lpFileContent,
  1890.                         analyzer.fileSize);
  1891.  
  1892.                     if (versionData && !IsBadReadPtr(versionData, sizeof(VS_FIXEDFILEINFO))) {
  1893.                         auto versionInfo = (VS_FIXEDFILEINFO*)(versionData + 40);
  1894.                         if (versionInfo->dwSignature == 0xFEEF04BD) {
  1895.                             for (int indent = 0; indent < level + 2; indent++) {
  1896.                                 OUTPUT("\t");
  1897.                             }
  1898.                             OUTPUT("File Version: %d.%d.%d.%d\n",
  1899.                                 HIWORD(versionInfo->dwFileVersionMS),
  1900.                                 LOWORD(versionInfo->dwFileVersionMS),
  1901.                                 HIWORD(versionInfo->dwFileVersionLS),
  1902.                                 LOWORD(versionInfo->dwFileVersionLS));
  1903.                         }
  1904.                     }
  1905.                 }
  1906.             }
  1907.         }
  1908.     }
  1909. }
  1910.  
  1911. void ParseResourceDirectory32(const PEAnalyzer& analyzer) {
  1912.     const auto& resourceDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
  1913.     if (!resourceDir.VirtualAddress || !resourceDir.Size) return;
  1914.  
  1915.     if (!PEHelpers::IsRvaValid(resourceDir.VirtualAddress, analyzer.fileSize,
  1916.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1917.         OUTPUT("[-] Invalid resource directory RVA!\n");
  1918.         throw std::runtime_error("RVA out of bounds");
  1919.         return;
  1920.     }
  1921.  
  1922.     OUTPUT("\n[+] RESOURCE DIRECTORY (32-bit)\n");
  1923.     auto pResourceDir = (PIMAGE_RESOURCE_DIRECTORY)PEHelpers::GetRvaPtr(
  1924.         resourceDir.VirtualAddress,
  1925.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1926.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1927.         analyzer.lpFileContent,
  1928.         analyzer.fileSize);
  1929.  
  1930.     if (!pResourceDir || IsBadReadPtr(pResourceDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1931.         OUTPUT("[-] Invalid or corrupted resource directory\n");
  1932.         return;
  1933.     }
  1934.  
  1935.     const wchar_t* resourceTypes[] = {
  1936.         L"Unknown",     L"Cursor",      L"Bitmap",      L"Icon",
  1937.         L"Menu",        L"Dialog",      L"String",      L"FontDir",
  1938.         L"Font",        L"Accelerator", L"RCData",      L"MessageTable",
  1939.         L"GroupCursor", L"GroupIcon",   L"Version",     L"DlgInclude"
  1940.     };
  1941.  
  1942.     ProcessResourceDirectory32(pResourceDir, 0, nullptr, pResourceDir, resourceTypes, analyzer);
  1943. }
  1944.  
  1945. void ParseDebugDirectory32(const PEAnalyzer& analyzer) {
  1946.     const auto& debugDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
  1947.     if (!debugDir.VirtualAddress || !debugDir.Size) return;
  1948.  
  1949.     if (!PEHelpers::IsRvaValid(debugDir.VirtualAddress, analyzer.fileSize,
  1950.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1951.         OUTPUT("[-] Invalid debug directory RVA!\n");
  1952.         throw std::runtime_error("RVA out of bounds");
  1953.         return;
  1954.     }
  1955.  
  1956.     OUTPUT("\n[+] DEBUG DIRECTORY (32-bit)\n");
  1957.     auto pDebugDir = (PIMAGE_DEBUG_DIRECTORY)PEHelpers::GetRvaPtr(
  1958.         debugDir.VirtualAddress,
  1959.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1960.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1961.         analyzer.lpFileContent,
  1962.         analyzer.fileSize);
  1963.  
  1964.     if (!pDebugDir || IsBadReadPtr(pDebugDir, sizeof(IMAGE_DEBUG_DIRECTORY))) {
  1965.         OUTPUT("[-] Invalid debug directory structure!\n");
  1966.         return;
  1967.     }
  1968.  
  1969.     DWORD numEntries = min(debugDir.Size / sizeof(IMAGE_DEBUG_DIRECTORY), 16);
  1970.     for (DWORD i = 0; i < numEntries; i++) {
  1971.         OUTPUT("\tDebug Entry %d:\n", i + 1);
  1972.         OUTPUT("\tCharacteristics: 0x%X\n", pDebugDir[i].Characteristics);
  1973.         OUTPUT("\tTimeDateStamp: 0x%X\n", pDebugDir[i].TimeDateStamp);
  1974.         OUTPUT("\tMajorVersion: %d\n", pDebugDir[i].MajorVersion);
  1975.         OUTPUT("\tMinorVersion: %d\n", pDebugDir[i].MinorVersion);
  1976.         OUTPUT("\tType: 0x%X", pDebugDir[i].Type);
  1977.  
  1978.         switch (pDebugDir[i].Type) {
  1979.         case IMAGE_DEBUG_TYPE_COFF:
  1980.             OUTPUT(" (COFF)\n"); break;
  1981.         case IMAGE_DEBUG_TYPE_CODEVIEW:
  1982.             OUTPUT(" (CodeView)\n"); break;
  1983.         case IMAGE_DEBUG_TYPE_FPO:
  1984.             OUTPUT(" (FPO)\n"); break;
  1985.         case IMAGE_DEBUG_TYPE_MISC:
  1986.             OUTPUT(" (Misc)\n"); break;
  1987.         case IMAGE_DEBUG_TYPE_EXCEPTION:
  1988.             OUTPUT(" (Exception)\n"); break;
  1989.         case IMAGE_DEBUG_TYPE_FIXUP:
  1990.             OUTPUT(" (Fixup)\n"); break;
  1991.         case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
  1992.             OUTPUT(" (OMAP to Src)\n"); break;
  1993.         case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
  1994.             OUTPUT(" (OMAP from Src)\n"); break;
  1995.         case IMAGE_DEBUG_TYPE_BORLAND:
  1996.             OUTPUT(" (Borland)\n"); break;
  1997.         default:
  1998.             OUTPUT(" (Unknown)\n"); break;
  1999.         }
  2000.  
  2001.         OUTPUT("\tSizeOfData: 0x%X\n", pDebugDir[i].SizeOfData);
  2002.         OUTPUT("\tAddressOfRawData: 0x%X\n", pDebugDir[i].AddressOfRawData);
  2003.         OUTPUT("\tPointerToRawData: 0x%X\n\n", pDebugDir[i].PointerToRawData);
  2004.  
  2005.         // Special handling for CodeView debug information
  2006.         if (pDebugDir[i].Type == IMAGE_DEBUG_TYPE_CODEVIEW &&
  2007.             pDebugDir[i].PointerToRawData != 0 &&
  2008.             pDebugDir[i].SizeOfData >= sizeof(DWORD)) {
  2009.  
  2010.             auto pCVHeader = (DWORD*)((BYTE*)analyzer.lpFileContent + pDebugDir[i].PointerToRawData);
  2011.             if (!IsBadReadPtr(pCVHeader, sizeof(DWORD))) {
  2012.                 switch (*pCVHeader) {
  2013.                 case 0x53445352: // 'RSDS'
  2014.                     if (pDebugDir[i].SizeOfData >= (sizeof(DWORD) + sizeof(GUID) + sizeof(DWORD) + 1)) {
  2015.                         auto pCVData = (char*)(pCVHeader + 1);
  2016.                         if (!IsBadReadPtr(pCVData + 16, 1)) {
  2017.                             auto guid = (GUID*)pCVData;
  2018.                             DWORD age = *(DWORD*)(pCVData + 16);
  2019.                             const char* pdbPath = pCVData + 20;
  2020.  
  2021.                             OUTPUT("\tPDB Information:\n");
  2022.                             OUTPUT("\tGUID: {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
  2023.                                 guid->Data1, guid->Data2, guid->Data3,
  2024.                                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  2025.                                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  2026.                             OUTPUT("\tAge: %d\n", age);
  2027.                             OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2028.                         }
  2029.                     }
  2030.                     break;
  2031.  
  2032.                 case 0x3031424E: // 'NB10'
  2033.                     if (pDebugDir[i].SizeOfData >= 16) {
  2034.                         auto pNB10Data = (char*)(pCVHeader + 1);
  2035.                         DWORD offset = *(DWORD*)pNB10Data;
  2036.                         DWORD timestamp = *(DWORD*)(pNB10Data + 4);
  2037.                         DWORD age = *(DWORD*)(pNB10Data + 8);
  2038.                         const char* pdbPath = pNB10Data + 12;
  2039.  
  2040.                         OUTPUT("\tPDB Information (NB10):\n");
  2041.                         OUTPUT("\tOffset: 0x%X\n", offset);
  2042.                         OUTPUT("\tTimestamp: 0x%X\n", timestamp);
  2043.                         OUTPUT("\tAge: %d\n", age);
  2044.                         OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2045.                     }
  2046.                     break;
  2047.                 }
  2048.             }
  2049.         }
  2050.     }
  2051. }
  2052.  
  2053. void ParseDebugDirectory64(const PEAnalyzer& analyzer) {
  2054.     const auto& debugDir = analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
  2055.     if (!debugDir.VirtualAddress || !debugDir.Size) return;
  2056.  
  2057.     if (!PEHelpers::IsRvaValid(debugDir.VirtualAddress, analyzer.fileSize,
  2058.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64))) {
  2059.         OUTPUT("[-] Invalid debug directory RVA!\n");
  2060.         throw std::runtime_error("RVA out of bounds");
  2061.         return;
  2062.     }
  2063.  
  2064.     OUTPUT("\n[+] DEBUG DIRECTORY (64-bit)\n");
  2065.     // Rest of implementation follows same pattern as 32-bit version
  2066.     // Just using pNtHeaders64 instead of pNtHeaders32
  2067.     auto pDebugDir = (PIMAGE_DEBUG_DIRECTORY)PEHelpers::GetRvaPtr(
  2068.         debugDir.VirtualAddress,
  2069.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  2070.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  2071.         analyzer.lpFileContent,
  2072.         analyzer.fileSize);
  2073.  
  2074.     if (!pDebugDir || IsBadReadPtr(pDebugDir, sizeof(IMAGE_DEBUG_DIRECTORY))) {
  2075.         OUTPUT("[-] Invalid debug directory structure!\n");
  2076.         return;
  2077.     }
  2078.  
  2079.     DWORD numEntries = min(debugDir.Size / sizeof(IMAGE_DEBUG_DIRECTORY), 16);
  2080.     for (DWORD i = 0; i < numEntries; i++) {
  2081.         OUTPUT("\tDebug Entry %d:\n", i + 1);
  2082.         OUTPUT("\tCharacteristics: 0x%X\n", pDebugDir[i].Characteristics);
  2083.         OUTPUT("\tTimeDateStamp: 0x%X\n", pDebugDir[i].TimeDateStamp);
  2084.         OUTPUT("\tMajorVersion: %d\n", pDebugDir[i].MajorVersion);
  2085.         OUTPUT("\tMinorVersion: %d\n", pDebugDir[i].MinorVersion);
  2086.         OUTPUT("\tType: 0x%X", pDebugDir[i].Type);
  2087.  
  2088.         switch (pDebugDir[i].Type) {
  2089.         case IMAGE_DEBUG_TYPE_COFF:
  2090.             OUTPUT(" (COFF)\n"); break;
  2091.         case IMAGE_DEBUG_TYPE_CODEVIEW:
  2092.             OUTPUT(" (CodeView)\n"); break;
  2093.         case IMAGE_DEBUG_TYPE_FPO:
  2094.             OUTPUT(" (FPO)\n"); break;
  2095.         case IMAGE_DEBUG_TYPE_MISC:
  2096.             OUTPUT(" (Misc)\n"); break;
  2097.         case IMAGE_DEBUG_TYPE_EXCEPTION:
  2098.             OUTPUT(" (Exception)\n"); break;
  2099.         case IMAGE_DEBUG_TYPE_FIXUP:
  2100.             OUTPUT(" (Fixup)\n"); break;
  2101.         case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
  2102.             OUTPUT(" (OMAP to Src)\n"); break;
  2103.         case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
  2104.             OUTPUT(" (OMAP from Src)\n"); break;
  2105.         case IMAGE_DEBUG_TYPE_BORLAND:
  2106.             OUTPUT(" (Borland)\n"); break;
  2107.         default:
  2108.             OUTPUT(" (Unknown)\n"); break;
  2109.         }
  2110.  
  2111.         OUTPUT("\tSizeOfData: 0x%X\n", pDebugDir[i].SizeOfData);
  2112.         OUTPUT("\tAddressOfRawData: 0x%X\n", pDebugDir[i].AddressOfRawData);
  2113.         OUTPUT("\tPointerToRawData: 0x%X\n\n", pDebugDir[i].PointerToRawData);
  2114.  
  2115.         // Special handling for CodeView debug information
  2116.         if (pDebugDir[i].Type == IMAGE_DEBUG_TYPE_CODEVIEW &&
  2117.             pDebugDir[i].PointerToRawData != 0 &&
  2118.             pDebugDir[i].SizeOfData >= sizeof(DWORD)) {
  2119.  
  2120.             auto pCVHeader = (DWORD*)((BYTE*)analyzer.lpFileContent + pDebugDir[i].PointerToRawData);
  2121.             if (!IsBadReadPtr(pCVHeader, sizeof(DWORD))) {
  2122.                 switch (*pCVHeader) {
  2123.                 case 0x53445352: // 'RSDS'
  2124.                     if (pDebugDir[i].SizeOfData >= (sizeof(DWORD) + sizeof(GUID) + sizeof(DWORD) + 1)) {
  2125.                         auto pCVData = (char*)(pCVHeader + 1);
  2126.                         if (!IsBadReadPtr(pCVData + 16, 1)) {
  2127.                             auto guid = (GUID*)pCVData;
  2128.                             DWORD age = *(DWORD*)(pCVData + 16);
  2129.                             const char* pdbPath = pCVData + 20;
  2130.  
  2131.                             OUTPUT("\tPDB Information:\n");
  2132.                             OUTPUT("\tGUID: {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
  2133.                                 guid->Data1, guid->Data2, guid->Data3,
  2134.                                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  2135.                                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  2136.                             OUTPUT("\tAge: %d\n", age);
  2137.                             OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2138.                         }
  2139.                     }
  2140.                     break;
  2141.  
  2142.                 case 0x3031424E: // 'NB10'
  2143.                     if (pDebugDir[i].SizeOfData >= 16) {
  2144.                         auto pNB10Data = (char*)(pCVHeader + 1);
  2145.                         DWORD offset = *(DWORD*)pNB10Data;
  2146.                         DWORD timestamp = *(DWORD*)(pNB10Data + 4);
  2147.                         DWORD age = *(DWORD*)(pNB10Data + 8);
  2148.                         const char* pdbPath = pNB10Data + 12;
  2149.  
  2150.                         OUTPUT("\tPDB Information (NB10):\n");
  2151.                         OUTPUT("\tOffset: 0x%X\n", offset);
  2152.                         OUTPUT("\tTimestamp: 0x%X\n", timestamp);
  2153.                         OUTPUT("\tAge: %d\n", age);
  2154.                         OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2155.                     }
  2156.                     break;
  2157.                 }
  2158.             }
  2159.         }
  2160.     }
  2161. }
  2162. // ... [Same implementation as ParseDebugDirectory32]
  2163.  
  2164. //newfunctionshere (lateest fixes)
  2165.  
  2166.  
  2167. void ProcessResourceDirectory32(
  2168.     PIMAGE_RESOURCE_DIRECTORY resDir,
  2169.     int level,
  2170.     const wchar_t* type,
  2171.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  2172.     const wchar_t* resourceTypes[],
  2173.     const PEAnalyzer& analyzer);
  2174.  
  2175. void ProcessResourceDirectory64(
  2176.     PIMAGE_RESOURCE_DIRECTORY resDir,
  2177.     int level,
  2178.     const wchar_t* type,
  2179.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  2180.     const wchar_t* resourceTypes[],
  2181.     const PEAnalyzer& analyzer);
  2182.  
  2183. // Main window class name
  2184. //const char* const WINDOW_CLASS_NAME = "PEAnalyzerWindow";
  2185.  
  2186. //new inserted here >>
  2187.  
  2188. // Page Break
  2189.  
  2190. //here
  2191.  
  2192. // Page Break
  2193.  
  2194. void AddMenus(HWND hwnd) {
  2195.     HMENU hMenuBar = CreateMenu();
  2196.     HMENU hFileMenu = CreateMenu();
  2197.     AppendMenu(hMenuBar, MF_POPUP, (UINT_PTR)hFileMenu, L"&File");
  2198.     AppendMenu(hFileMenu, MF_STRING, 1, L"&Open\tCtrl+O");  // Updated to show shortcut
  2199.     AppendMenu(hFileMenu, MF_STRING, 2, L"E&xit");
  2200.     SetMenu(hwnd, hMenuBar);
  2201. }
  2202.  
  2203. // First, add this helper function to determine if the PE file is 64-bit
  2204. bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2205.     return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2206. } //removing this duplicate
  2207.  
  2208. // Helper function to safely get file size
  2209. /*DWORD GetFileSizeCustom(const wchar_t* filePath) {
  2210.     HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ,
  2211.         nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  2212.  
  2213.     if (hFile == INVALID_HANDLE_VALUE) {
  2214.         return 0;
  2215.     }
  2216.  
  2217.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  2218.     CloseHandle(hFile);
  2219.     return fileSize;
  2220. }*/ //removing this duplicate instead
  2221.  
  2222. // Add this helper function
  2223. void SafeOutput(const std::wstring& text) {
  2224.     try {
  2225.         g_OutputText << text;
  2226.         UpdateEditControl();
  2227.     }
  2228.     catch (...) {
  2229.         SetStatusText(L"Error writing output");
  2230.     }
  2231. }
  2232.  
  2233. void UpdateStatusBar(const wchar_t* text, int progress = -1) {
  2234.     if (text) {
  2235.         SetStatusText(text);
  2236.     }
  2237.     if (progress >= 0) {
  2238.         ShowProgress(progress);
  2239.     }
  2240. }
  2241.  
  2242. void ClearProgress() {
  2243.     ShowWindow(g_hProgressBar, SW_HIDE);
  2244.     SetStatusText(L"Ready");
  2245. }
  2246.  
  2247.  
  2248.  
  2249. void SetStatusText(const wchar_t* text) {
  2250.     SendMessage(g_hStatusBar, SB_SETTEXT, 0, (LPARAM)text);
  2251. }
  2252.  
  2253. void ShowProgress(int percentage) {
  2254.     // Update progress bar
  2255.     SendMessage(g_hProgressBar, PBM_SETPOS, (WPARAM)percentage, 0);
  2256.  
  2257.     // Update status text in first part
  2258.     wchar_t status[256];
  2259.     swprintf_s(status, L"Analyzing... %d%%", percentage);
  2260.     //swprintf_s(status, L"Analyzing...");
  2261.     SetStatusText(status); //commented-out
  2262.     SendMessage(g_hStatusBar, SB_SETTEXT, 0, (LPARAM)status);
  2263. }
  2264.  
  2265. void OpenFileDialog(HWND hwnd) {
  2266.     WCHAR fileName[MAX_PATH] = L"";
  2267.     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 };
  2268.     if (GetOpenFileNameW(&ofn)) {
  2269.         SetWindowTextW(g_hEditControl, L"");
  2270.         g_OutputText.str(L"");
  2271.         g_OutputText.clear();
  2272.         AnalyzePEFile(ofn.lpstrFile);
  2273.         UpdateEditControl();
  2274.     }
  2275. }
  2276.  
  2277.  
  2278. // Modified AppendToOutput to handle newlines properly:
  2279. void AppendToOutput(const wchar_t* format, ...) {
  2280.     std::vector<wchar_t> buffer(1024);
  2281.     va_list args;
  2282.     va_start(args, format);
  2283.  
  2284.     while (true) {
  2285.         int result = _vsnwprintf(buffer.data(), buffer.size(), format, args);
  2286.         if (result >= 0) break;
  2287.         buffer.resize(buffer.size() * 2);
  2288.     }
  2289.     va_end(args);
  2290.  
  2291.     // Convert \n to \r\n
  2292.     std::wstring output = buffer.data();
  2293.     size_t pos = 0;
  2294.     while ((pos = output.find(L'\n', pos)) != std::wstring::npos) {
  2295.         if (pos == 0 || output[pos - 1] != L'\r') {
  2296.             output.insert(pos, L"\r");
  2297.             pos += 2;
  2298.         }
  2299.         else {
  2300.             pos++;
  2301.         }
  2302.     }
  2303.  
  2304.     g_OutputText << output;
  2305.     UpdateEditControl();
  2306. }
  2307.  
  2308.  
  2309. //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    
  2310.  
  2311. //adding here
  2312. // Line Break
  2313. // new code below starting here vv
  2314.  
  2315.  
  2316.  
  2317. DWORD GetFileSize(const wchar_t* filePath) {
  2318.     HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ,
  2319.         nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  2320.     if (hFile == INVALID_HANDLE_VALUE) return 0;
  2321.  
  2322.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  2323.     CloseHandle(hFile);
  2324.     return fileSize;
  2325. }
  2326. //}
  2327. // Page Break
  2328.  
  2329. //}
  2330.  
  2331. //UpdateEditControl();
  2332. //}
  2333.  
  2334. // new code upto here ending here ^^
  2335. // Line Break
  2336. //  //end adding here
  2337.  
  2338.  
  2339.  
  2340. //filePathW
  2341. //lpFilePath
  2342. HANDLE GetFileContent(const wchar_t* lpFilePath) {
  2343.     HANDLE hFile = CreateFileW(lpFilePath, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
  2344.     if (hFile == INVALID_HANDLE_VALUE) return nullptr;
  2345.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  2346.     auto lpFileContent = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, fileSize);
  2347.     DWORD bytesRead;
  2348.     ReadFile(hFile, lpFileContent, fileSize, &bytesRead, nullptr);
  2349.     CloseHandle(hFile);
  2350.     return lpFileContent;
  2351. }
  2352.  
  2353. void UpdateEditControl() {
  2354.     SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
  2355.     SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
  2356.     SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
  2357. }
  2358. //}
  2359.  
  2360. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
  2361.     INITCOMMONCONTROLSEX icc = { sizeof(INITCOMMONCONTROLSEX), ICC_WIN95_CLASSES };
  2362.     InitCommonControlsEx(&icc);
  2363.  
  2364.     // Get command line parameters in Unicode
  2365.     int argc;
  2366.     LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  2367.  
  2368.     CreateMainWindow(hInstance);
  2369.     if (!g_hMainWindow) {
  2370.         LocalFree(argv);
  2371.         return -1;
  2372.     }
  2373.  
  2374.     ShowWindow(g_hMainWindow, nCmdShow);
  2375.     UpdateWindow(g_hMainWindow);
  2376.  
  2377.     // If there's a command line parameter, process it
  2378.     if (argc > 1) {
  2379.         // Process the first parameter as file path
  2380.         SetWindowTextW(g_hEditControl, L"");
  2381.         g_OutputText.str(L"");
  2382.         g_OutputText.clear();
  2383.         AnalyzePEFile(argv[1]);
  2384.         UpdateEditControl();
  2385.     }
  2386.  
  2387.     LocalFree(argv);
  2388.  
  2389.     MSG msg = {};
  2390.     while (GetMessage(&msg, NULL, 0, 0)) {
  2391.         TranslateMessage(&msg);
  2392.         DispatchMessage(&msg);
  2393.     }
  2394.  
  2395.     if (g_hFont) DeleteObject(g_hFont);
  2396.     return (int)msg.wParam;
  2397. }
  2398.  
  2399. void CreateMainWindow(HINSTANCE hInstance) {
  2400.     WNDCLASSEXW wc = { sizeof(WNDCLASSEXW), 0, WindowProc, 0, 0, hInstance,
  2401.         LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)),
  2402.         LoadCursor(NULL, IDC_ARROW),
  2403.         (HBRUSH)(COLOR_WINDOW + 1),
  2404.         NULL, WINDOW_CLASS_NAME,
  2405.         LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)) };
  2406.     RegisterClassExW(&wc);
  2407.  
  2408.     // Get screen dimensions
  2409.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  2410.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  2411.  
  2412.     // Calculate center position
  2413.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  2414.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  2415.  
  2416.     // Remove WS_MAXIMIZEBOX and WS_THICKFRAME from the window style
  2417.     DWORD style = (WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX) & ~WS_THICKFRAME;
  2418.     //WS_OVERLAPPEDWINDOW ~~> style
  2419.     g_hMainWindow = CreateWindowExW(0, WINDOW_CLASS_NAME, L"PE File Analyzer",
  2420.         style, windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  2421.         nullptr, nullptr, hInstance, nullptr);
  2422. }
  2423.  
  2424. void InitializeControls(HWND hwnd) {
  2425.     // Create status bar
  2426.     g_hStatusBar = CreateWindowEx(0, STATUSCLASSNAME, NULL,
  2427.         WS_CHILD | WS_VISIBLE,
  2428.         0, 0, 0, 0, hwnd, NULL,
  2429.         (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL);
  2430.  
  2431.     // Set up status bar parts
  2432.     RECT rcClient;
  2433.     GetClientRect(hwnd, &rcClient);
  2434.     int statusParts[2] = { 150, rcClient.right };
  2435.     SendMessage(g_hStatusBar, SB_SETPARTS, 2, (LPARAM)statusParts);
  2436.  
  2437.     // Create progress bar in the second part of status bar
  2438.     RECT rcPart;
  2439.     SendMessage(g_hStatusBar, SB_GETRECT, 1, (LPARAM)&rcPart);
  2440.  
  2441.     g_hProgressBar = CreateWindowEx(0, PROGRESS_CLASS, NULL,
  2442.         WS_CHILD | WS_VISIBLE | PBS_SMOOTH,
  2443.         rcPart.left + 5, rcPart.top + 2,
  2444.         rcPart.right - rcPart.left - 10, rcPart.bottom - rcPart.top - 4,
  2445.         g_hStatusBar, NULL,
  2446.         (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL);
  2447.  
  2448.     // Set blue color and range
  2449.     SendMessage(g_hProgressBar, PBM_SETBARCOLOR, 0, (LPARAM)RGB(0, 120, 215));  // Windows 10 blue
  2450.     SendMessage(g_hProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
  2451.     SendMessage(g_hProgressBar, PBM_SETSTEP, 1, 0);
  2452.  
  2453.     // Get status bar height for edit control positioning
  2454.     RECT rcStatus;
  2455.     GetWindowRect(g_hStatusBar, &rcStatus);
  2456.     int statusHeight = rcStatus.bottom - rcStatus.top;
  2457.  
  2458.     // Create edit control
  2459.     g_hEditControl = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
  2460.         WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL |
  2461.         ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL,
  2462.         EDIT_MARGIN, EDIT_MARGIN,
  2463.         rcClient.right - (2 * EDIT_MARGIN),
  2464.         rcClient.bottom - statusHeight - (2 * EDIT_MARGIN),
  2465.         hwnd, nullptr,
  2466.         (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), nullptr);
  2467.  
  2468.     // Create and set font
  2469.     g_hFont = CreateFont(-14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0,
  2470.         ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
  2471.         DEFAULT_QUALITY, DEFAULT_PITCH | FF_MODERN, L"Consolas");
  2472.  
  2473.     if (g_hFont)
  2474.         SendMessage(g_hEditControl, WM_SETFONT, (WPARAM)g_hFont, TRUE);
  2475.  
  2476.     SetWindowSubclass(g_hEditControl, EditSubclassProc, 0, 0);
  2477. }
  2478.  
  2479. LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) {
  2480.     if (uMsg == WM_KEYDOWN) {
  2481.         if ((GetKeyState(VK_CONTROL) & 0x8000) && wParam == 'O') {
  2482.             SendMessage(GetParent(hwnd), WM_COMMAND, 1, 0);
  2483.             return 0;
  2484.         }
  2485.         switch (wParam) {
  2486.         case VK_F1:
  2487.             SendMessage(GetParent(hwnd), WM_KEYDOWN, VK_F1, 0);
  2488.             return 0;
  2489.         case VK_ESCAPE:
  2490.             SendMessage(GetParent(hwnd), WM_KEYDOWN, VK_ESCAPE, 0);
  2491.             return 0;
  2492.         case VK_PRIOR:
  2493.             // Scroll up
  2494.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2495.             return 0;
  2496.         case VK_NEXT:
  2497.             // Scroll down
  2498.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2499.             return 0;
  2500.         case VK_UP:
  2501.             // Scroll one line up
  2502.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_LINEUP, 0), 0);
  2503.             return 0;
  2504.         case VK_DOWN:
  2505.             // Scroll one line down
  2506.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_LINEDOWN, 0), 0);
  2507.             return 0;
  2508.         }
  2509.     }
  2510.     if (uMsg == WM_MOUSEWHEEL) {
  2511.         int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  2512.         if (delta > 0) {
  2513.             // Scroll up
  2514.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2515.         }
  2516.         else {
  2517.             // Scroll down
  2518.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2519.         }
  2520.         return 0;
  2521.     }
  2522.     return DefSubclassProc(hwnd, uMsg, wParam, lParam);
  2523. }
  2524.  
  2525. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  2526.     switch (uMsg) {
  2527.     case WM_CREATE: InitializeControls(hwnd); AddMenus(hwnd); return 0;
  2528.     case WM_SIZE:
  2529.     {
  2530.         RECT rcClient;
  2531.         GetClientRect(hwnd, &rcClient);
  2532.  
  2533.         // Resize status bar
  2534.         SendMessage(g_hStatusBar, WM_SIZE, 0, 0);
  2535.  
  2536.         // Recalculate status bar parts
  2537.         int statusParts[2] = { 150, rcClient.right };
  2538.         SendMessage(g_hStatusBar, SB_SETPARTS, 2, (LPARAM)statusParts);
  2539.  
  2540.         // Reposition progress bar
  2541.         RECT rcPart;
  2542.         SendMessage(g_hStatusBar, SB_GETRECT, 1, (LPARAM)&rcPart);
  2543.         SetWindowPos(g_hProgressBar, NULL,
  2544.             rcPart.left + 5, rcPart.top + 2,
  2545.             rcPart.right - rcPart.left - 10, rcPart.bottom - rcPart.top - 4,
  2546.             SWP_NOZORDER);
  2547.  
  2548.         // Get status bar height
  2549.         RECT rcStatus;
  2550.         GetWindowRect(g_hStatusBar, &rcStatus);
  2551.         int statusHeight = rcStatus.bottom - rcStatus.top;
  2552.  
  2553.         // Resize edit control
  2554.         SetWindowPos(g_hEditControl, NULL,
  2555.             EDIT_MARGIN,
  2556.             EDIT_MARGIN,
  2557.             rcClient.right - (2 * EDIT_MARGIN),
  2558.             rcClient.bottom - statusHeight - (2 * EDIT_MARGIN),
  2559.             SWP_NOZORDER);
  2560.         return 0;
  2561.     }
  2562.  
  2563.     case WM_KEYDOWN:
  2564.     {
  2565.         if (GetKeyState(VK_CONTROL) & 0x8000) {
  2566.             switch (wParam) {
  2567.             case 'O':
  2568.                 OpenFileDialog(hwnd);
  2569.                 return 0;
  2570.             }
  2571.         }
  2572.         switch (wParam) {
  2573.         case VK_F1:
  2574.             MessageBoxW(hwnd,
  2575.                 L"PE Header Parser 4.3 GUI-based Programmed in C++ Win32 API (1546 lines of code) by Entisoft Software(c) Evans Thorpemorton",
  2576.                 L"About",
  2577.                 MB_OK | MB_ICONINFORMATION);
  2578.             return 0;
  2579.         case VK_ESCAPE:
  2580.             PostQuitMessage(0);
  2581.             return 0;
  2582.         case VK_PRIOR:
  2583.             // Scroll up
  2584.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2585.             return 0;
  2586.         case VK_NEXT:
  2587.             // Scroll down
  2588.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2589.             return 0;
  2590.         case VK_UP:
  2591.             // Scroll one line up
  2592.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_LINEUP, 0), 0);
  2593.             return 0;
  2594.         case VK_DOWN:
  2595.             // Scroll one line down
  2596.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_LINEDOWN, 0), 0);
  2597.             return 0;
  2598.         }
  2599.         break;
  2600.     }
  2601.     case WM_MOUSEWHEEL:
  2602.     {
  2603.         int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  2604.         if (delta > 0) {
  2605.             // Scroll up
  2606.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2607.         }
  2608.         else {
  2609.             // Scroll down
  2610.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2611.         }
  2612.         return 0;
  2613.     }
  2614.     case WM_COMMAND: if (LOWORD(wParam) == 1) OpenFileDialog(hwnd); if (LOWORD(wParam) == 2) PostQuitMessage(0); return 0;
  2615.     case WM_DESTROY:
  2616.         if (g_hStatusBar) DestroyWindow(g_hStatusBar);
  2617.         PostQuitMessage(0);
  2618.         return 0;
  2619.     }
  2620.     return DefWindowProc(hwnd, uMsg, wParam, lParam);
  2621. }
  2622.  
  2623. ===+++PEHeaders.h+++===
  2624. #pragma once
  2625. #ifndef PE_ANALYZER_STRUCT_H
  2626. #define PE_ANALYZER_STRUCT_H
  2627. #include <Windows.h>
  2628. #include <winternl.h>
  2629.  
  2630. // Core PE analysis structure
  2631. struct PEAnalyzer {
  2632.     LPVOID lpFileContent;
  2633.     DWORD fileSize;
  2634.     bool is64Bit;
  2635.     PIMAGE_NT_HEADERS32 pNtHeaders32;
  2636.     PIMAGE_NT_HEADERS64 pNtHeaders64;
  2637.     PIMAGE_DOS_HEADER pDosHeader;
  2638.  
  2639.     PEAnalyzer() : lpFileContent(nullptr), fileSize(0), is64Bit(false),
  2640.         pNtHeaders32(nullptr), pNtHeaders64(nullptr), pDosHeader(nullptr) {}
  2641.  
  2642.     ~PEAnalyzer() {
  2643.         if (lpFileContent) {
  2644.             UnmapViewOfFile(lpFileContent);
  2645.             lpFileContent = nullptr;
  2646.         }
  2647.     }
  2648. };
  2649. //struct PEAnalyzer;  // Add this before the namespace
  2650. // Declare functions that use PEAnalyzer
  2651.     template<typename T>
  2652.     bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size);
  2653. #endif // PE_ANALYZER_STRUCT_H
  2654. namespace PEHelpers {
  2655. //ifndef OUTPUT was here
  2656.  
  2657.     // Inline function to prevent multiple definition
  2658.     inline bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2659.         return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2660.     }
  2661.     //bool ValidateFileSize(const PEAnalyzer& analyzer, DWORD expectedSize, DWORD fileSize);
  2662.     bool ValidateFileSize(DWORD expectedSize, DWORD fileSize);
  2663.     // Add the template function declaration here
  2664.     //template<typename T>
  2665.     //bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size);
  2666.     bool IsRvaValid(DWORD rva, DWORD fileSize, PIMAGE_NT_HEADERS pNtHeaders);
  2667.     DWORD_PTR GetImageBase(PIMAGE_NT_HEADERS pNtHeaders);
  2668.     DWORD GetSizeOfImage(PIMAGE_NT_HEADERS pNtHeaders);
  2669.     DWORD_PTR GetRvaPtr(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader,
  2670.         WORD numberOfSections, LPVOID baseAddress);
  2671.     DWORD RvaToOffset(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader,
  2672.         WORD numberOfSections);
  2673.     std::wstring GetImageCharacteristics(DWORD characteristics);
  2674.     std::wstring GetSubsystem(WORD subsystem);
  2675.     std::wstring GetDataDirectoryName(int DirectoryNumber);
  2676.     std::wstring GetSectionProtection(DWORD characteristics);
  2677.  
  2678.     //    using namespace std;
  2679.     //    using namespace PEAnalyzer;
  2680.         // Core PE validation functions
  2681.     // Ensure this function is defined exactly once
  2682.     /*inline bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2683.         return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2684.     }*/
  2685.  
  2686. /*bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2687.     return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2688. }*/
  2689.  
  2690. bool ValidateFileSize(DWORD expectedSize, DWORD fileSize) {
  2691.     return expectedSize > 0 && expectedSize <= fileSize;
  2692. }
  2693.  
  2694. template<typename T>
  2695. bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size = sizeof(T)) {
  2696.     // Check if pointer is null
  2697.     if (!ptr) {
  2698.         OUTPUT("[-] Null pointer detected\n");
  2699.         return false;
  2700.     }
  2701.  
  2702.     // Calculate pointer ranges
  2703.     DWORD_PTR startAddress = reinterpret_cast<DWORD_PTR>(analyzer.lpFileContent);
  2704.     DWORD_PTR endAddress = startAddress + analyzer.fileSize;
  2705.     DWORD_PTR ptrAddress = reinterpret_cast<DWORD_PTR>(ptr);
  2706.     DWORD_PTR ptrEndAddress = ptrAddress + size;
  2707.  
  2708.     // Comprehensive pointer validation
  2709.     bool isValidPointer = (
  2710.         ptr != nullptr &&                  // Not null
  2711.         ptrAddress >= startAddress &&       // Above file start
  2712.         ptrEndAddress <= endAddress &&      // Below file end
  2713.         ptrAddress < ptrEndAddress          // Prevent integer overflow
  2714.         );
  2715.  
  2716.     if (!isValidPointer) {
  2717.         OUTPUT("[-] Pointer validation failed\n");
  2718.         OUTPUT("    Pointer: 0x%p\n", ptr);
  2719.         OUTPUT("    File Start: 0x%p\n", reinterpret_cast<void*>(startAddress));
  2720.         OUTPUT("    File End: 0x%p\n", reinterpret_cast<void*>(endAddress));
  2721.         OUTPUT("    Pointer Start: 0x%p\n", reinterpret_cast<void*>(ptrAddress));
  2722.         OUTPUT("    Pointer End: 0x%p\n", reinterpret_cast<void*>(ptrEndAddress));
  2723.         return false;
  2724.     }
  2725.  
  2726.     return true;
  2727. }
  2728.  
  2729. bool IsRvaValid(DWORD rva, DWORD fileSize, PIMAGE_NT_HEADERS pNtHeaders) {
  2730.     if (!pNtHeaders) {
  2731.         OUTPUT("[-] Invalid NT Headers for RVA validation\n");
  2732.         return false;
  2733.     }
  2734.  
  2735.     DWORD sizeOfImage = PEHelpers::Is64BitPE(pNtHeaders) ?
  2736.         reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders)->OptionalHeader.SizeOfImage :
  2737.         reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders)->OptionalHeader.SizeOfImage;
  2738.  
  2739.     bool isValid = (
  2740.         rva > 0 &&                  // RVA is non-zero
  2741.         rva < sizeOfImage&&         // RVA is within image size
  2742.         rva < fileSize               // RVA is within file size
  2743.         );
  2744.  
  2745.     if (!isValid) {
  2746.         OUTPUT("[-] Invalid RVA: 0x%X\n", rva);
  2747.         OUTPUT("    Size of Image: 0x%X\n", sizeOfImage);
  2748.         OUTPUT("    File Size: 0x%X\n", fileSize);
  2749.     }
  2750.  
  2751.     return isValid;
  2752. }
  2753.  
  2754. /*bool IsRvaValid(DWORD rva, DWORD fileSize, PIMAGE_NT_HEADERS pNtHeaders) {
  2755.     return rva < pNtHeaders->OptionalHeader.SizeOfImage&& rva < fileSize;
  2756. }*/
  2757.  
  2758. DWORD_PTR GetImageBase(PIMAGE_NT_HEADERS pNtHeaders) {
  2759.     if (PEHelpers::Is64BitPE(pNtHeaders)) {  // Add PEHelpers:: namespace qualifier
  2760.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2761.         return static_cast<DWORD_PTR>(pNtHeaders64->OptionalHeader.ImageBase);
  2762.     }
  2763.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2764.     return static_cast<DWORD_PTR>(pNtHeaders32->OptionalHeader.ImageBase);
  2765. }
  2766.  
  2767. DWORD GetSizeOfImage(PIMAGE_NT_HEADERS pNtHeaders) {
  2768.     if (PEHelpers::Is64BitPE(pNtHeaders)) {  // Add PEHelpers:: namespace qualifier
  2769.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2770.         return pNtHeaders64->OptionalHeader.SizeOfImage;
  2771.     }
  2772.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2773.     return pNtHeaders32->OptionalHeader.SizeOfImage;
  2774. }
  2775.  
  2776. /* // RVA and address conversion helpers
  2777. DWORD_PTR GetImageBase(PIMAGE_NT_HEADERS pNtHeaders) {
  2778.     if (Is64BitPE(pNtHeaders)) {
  2779.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2780.         return static_cast<DWORD_PTR>(pNtHeaders64->OptionalHeader.ImageBase);
  2781.     }
  2782.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2783.     return static_cast<DWORD_PTR>(pNtHeaders32->OptionalHeader.ImageBase);
  2784. }
  2785.  
  2786. DWORD GetSizeOfImage(PIMAGE_NT_HEADERS pNtHeaders) {
  2787.     if (Is64BitPE(pNtHeaders)) {
  2788.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2789.         return pNtHeaders64->OptionalHeader.SizeOfImage;
  2790.     }
  2791.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2792.     return pNtHeaders32->OptionalHeader.SizeOfImage;
  2793. }*/
  2794.  
  2795. DWORD_PTR GetRvaPtr(
  2796.     DWORD rva,
  2797.     PIMAGE_SECTION_HEADER pSectionHeader,
  2798.     WORD numberOfSections,
  2799.     LPVOID baseAddress,
  2800.     DWORD fileSize  // Add file size as a parameter
  2801. ) {
  2802.     if (!rva || !pSectionHeader || !baseAddress) {
  2803.         OUTPUT("[-] Invalid parameters in GetRvaPtr\n");
  2804.         return 0;
  2805.     }
  2806.  
  2807.     for (WORD i = 0; i < numberOfSections; i++) {
  2808.         // Check if RVA falls within this section
  2809.         if (rva >= pSectionHeader[i].VirtualAddress &&
  2810.             rva < (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData)) {
  2811.  
  2812.             // Calculate pointer
  2813.             DWORD_PTR delta = reinterpret_cast<DWORD_PTR>(baseAddress) +
  2814.                 pSectionHeader[i].PointerToRawData;
  2815.  
  2816.             DWORD_PTR result = delta + (rva - pSectionHeader[i].VirtualAddress);
  2817.  
  2818.             // Additional validation
  2819.             if (result < reinterpret_cast<DWORD_PTR>(baseAddress) ||
  2820.                 result >= (reinterpret_cast<DWORD_PTR>(baseAddress) + fileSize)) {
  2821.                 OUTPUT("[-] RVA pointer out of bounds\n");
  2822.                 return 0;
  2823.             }
  2824.  
  2825.             return result;
  2826.         }
  2827.     }
  2828.  
  2829.     OUTPUT("[-] RVA not found in any section: 0x%X\n", rva);
  2830.     return 0;
  2831. }
  2832. //}
  2833. //}
  2834.  
  2835. /* DWORD_PTR GetRvaPtr(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader,
  2836.     WORD numberOfSections, LPVOID baseAddress) {
  2837.     if (!rva || !pSectionHeader || !baseAddress) return 0;
  2838.  
  2839.     for (WORD i = 0; i < numberOfSections; i++) {
  2840.         if (rva >= pSectionHeader[i].VirtualAddress &&
  2841.             rva < (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData)) {
  2842.             DWORD_PTR delta = (DWORD_PTR)baseAddress + pSectionHeader[i].PointerToRawData;
  2843.             return delta + (rva - pSectionHeader[i].VirtualAddress);
  2844.         }
  2845.     }
  2846.     OUTPUT("[-] Failed to map RVA: 0x%X\n", rva);
  2847.     return 0;
  2848. } */
  2849.  
  2850. DWORD RvaToOffset(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader, WORD numberOfSections) {
  2851.     if (!rva || !pSectionHeader) return 0;
  2852.  
  2853.     for (WORD i = 0; i < numberOfSections; i++) {
  2854.         if (rva >= pSectionHeader[i].VirtualAddress &&
  2855.             rva < (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData)) {
  2856.             return (rva - pSectionHeader[i].VirtualAddress) + pSectionHeader[i].PointerToRawData;
  2857.         }
  2858.     }
  2859.     OUTPUT("[-] Failed to map RVA: 0x%X\n", rva);
  2860.     return 0;
  2861. }
  2862.  
  2863. // PE information helper functions
  2864. std::wstring GetImageCharacteristics(DWORD characteristics) {
  2865.     if (characteristics & IMAGE_FILE_DLL) return L"(DLL)";
  2866.     if (characteristics & IMAGE_FILE_SYSTEM) return L"(DRIVER)";
  2867.     if (characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) return L"(EXE)";
  2868.     return L"(UNKNOWN)";
  2869. }
  2870.  
  2871. std::wstring GetSubsystem(WORD subsystem) {
  2872.     switch (subsystem) {
  2873.     case IMAGE_SUBSYSTEM_NATIVE: return L"(NATIVE/DRIVER)";
  2874.     case IMAGE_SUBSYSTEM_WINDOWS_GUI: return L"(GUI)";
  2875.     case IMAGE_SUBSYSTEM_WINDOWS_CUI: return L"(CONSOLE)";
  2876.     default: return L"(UNKNOWN)";
  2877.     }
  2878. }
  2879.  
  2880. std::wstring GetDataDirectoryName(int DirectoryNumber) {
  2881.     static const wchar_t* names[] = {
  2882.         L"Export Table", L"Import Table", L"Resource Table",
  2883.         L"Exception Entry", L"Security Entry", L"Relocation Table",
  2884.         L"Debug Entry", L"Copyright Entry", L"Global PTR Entry",
  2885.         L"TLS Entry", L"Configuration Entry", L"Bound Import Entry",
  2886.         L"IAT", L"Delay Import Descriptor", L"COM Descriptor"
  2887.     };
  2888.     return (DirectoryNumber < 15) ? names[DirectoryNumber] : L"Unknown";
  2889. }
  2890.  
  2891. std::wstring GetSectionProtection(DWORD characteristics) {
  2892.     std::wstring protection = L"(";
  2893.     bool needsSeparator = false;
  2894.  
  2895.     if (characteristics & IMAGE_SCN_MEM_EXECUTE) {
  2896.         protection += L"EXECUTE";
  2897.         needsSeparator = true;
  2898.     }
  2899.     if (characteristics & IMAGE_SCN_MEM_READ) {
  2900.         if (needsSeparator) protection += L" | ";
  2901.         protection += L"READ";
  2902.         needsSeparator = true;
  2903.     }
  2904.     if (characteristics & IMAGE_SCN_MEM_WRITE) {
  2905.         if (needsSeparator) protection += L" | ";
  2906.         protection += L"WRITE";
  2907.     }
  2908.     protection += L")";
  2909.     return protection;
  2910. }
  2911. }
Add Comment
Please, Sign In to add comment