alien_fx_fiend

Bkp B4 You,com Fixes

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