| 299 | |
| 300 | |
| 301 | std::vector<ModuleSection> EnumerateModuleSections(HANDLE hProcess, LPVOID moduleBase) { |
| 302 | std::vector<ModuleSection> moduleSections; |
| 303 | |
| 304 | if (!hProcess || hProcess == INVALID_HANDLE_VALUE || !moduleBase) { |
| 305 | LOG_A(LOG_ERROR, "EnumerateModuleSections: Invalid parameters"); |
| 306 | return moduleSections; |
| 307 | } |
| 308 | |
| 309 | // Buffer for headers |
| 310 | IMAGE_DOS_HEADER dosHeader = {}; |
| 311 | IMAGE_NT_HEADERS ntHeaders = {}; |
| 312 | std::vector<IMAGE_SECTION_HEADER> sectionHeaders; |
| 313 | |
| 314 | // Buffer for module name |
| 315 | wchar_t moduleName[MAX_PATH] = { 0 }; |
| 316 | if (!GetModuleBaseName(hProcess, (HMODULE)moduleBase, moduleName, MAX_PATH)) { |
| 317 | LOG_A(LOG_WARNING, "ProcessQuery: Failed to retrieve module name. Error: %lu", GetLastError()); |
| 318 | return moduleSections; |
| 319 | } |
| 320 | std::string moduleNameStr = wchar2string(moduleName); |
| 321 | |
| 322 | // Read the DOS header |
| 323 | if (!ReadProcessMemory(hProcess, moduleBase, &dosHeader, sizeof(dosHeader), NULL)) { |
| 324 | LOG_A(LOG_WARNING, "ProcessQuery: Failed to read DOS header. Error: %lu", GetLastError()); |
| 325 | return moduleSections; |
| 326 | } |
| 327 | // Verify DOS signature |
| 328 | if (dosHeader.e_magic != IMAGE_DOS_SIGNATURE) { |
| 329 | LOG_A(LOG_WARNING, "ProcessQuery: Invalid DOS signature. Not a valid PE file"); |
| 330 | return moduleSections; |
| 331 | } |
| 332 | |
| 333 | // Bounds check for e_lfanew |
| 334 | if (dosHeader.e_lfanew < 0 || dosHeader.e_lfanew > 0x10000) { |
| 335 | LOG_A(LOG_WARNING, "ProcessQuery: Invalid e_lfanew value: %ld", dosHeader.e_lfanew); |
| 336 | return moduleSections; |
| 337 | } |
| 338 | |
| 339 | // Read the NT header |
| 340 | LPVOID ntHeaderAddress = (LPBYTE)moduleBase + dosHeader.e_lfanew; |
| 341 | if (!ReadProcessMemory(hProcess, ntHeaderAddress, &ntHeaders, sizeof(ntHeaders), NULL)) { |
| 342 | LOG_A(LOG_WARNING, "ProcessQuery: Failed to read NT headers. Error: %lu", GetLastError()); |
| 343 | return moduleSections; |
| 344 | } |
| 345 | // Verify NT signature |
| 346 | if (ntHeaders.Signature != IMAGE_NT_SIGNATURE) { |
| 347 | LOG_A(LOG_WARNING, "ProcessQuery: Invalid NT signature. Not a valid PE file."); |
| 348 | return moduleSections; |
| 349 | } |
| 350 | |
| 351 | // Read section headers |
| 352 | DWORD numberOfSections = ntHeaders.FileHeader.NumberOfSections; |
| 353 | if (numberOfSections == 0 || numberOfSections > 96) { // Reasonable upper limit for sections |
| 354 | LOG_A(LOG_WARNING, "ProcessQuery: Invalid number of sections: %lu", numberOfSections); |
| 355 | return moduleSections; |
| 356 | } |
| 357 | |
| 358 | LPVOID sectionHeaderAddress = (LPBYTE)ntHeaderAddress + sizeof(IMAGE_NT_HEADERS); |