#include <iostream> #include <windows.h> #include <psapi.h> #include <fstream> #include…
- User
#include #include <windows.h> #include <psapi.h> #include #include #include #include #include #include <Zydis/Zydis.h>
// Ensure that you have the correct library linkage #pragma comment(lib, "psapi.lib")
class Logger { public: explicit Logger(const std::string& filepath) : logFilePath(filepath) { InitLog(); }
void Log(const std::string& message, const std::string& level = "INFO") { std::ofstream logFile(logFilePath, std::ios::app); if (logFile.is_open()) { logFile << "[" << GetFormattedTime() << "] [" << level << "] " << message << "\n"; } }private: std::string logFilePath;
void InitLog() { std::ofstream logFile(logFilePath, std::ios::trunc); if (logFile.is_open()) { logFile << "[" << GetFormattedTime() << "] [INIT] Log initiated\n"; } } std::string GetFormattedTime() { std::time_t currentTime = std::time(nullptr); char buffer[100]; struct tm timeInfo; localtime_s(&timeInfo, ¤tTime); std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &timeInfo); return std::string(buffer); }};
DWORD GetProcessIdByName(const std::wstring& processName) { DWORD processIds[1024], cbNeeded; if (!EnumProcesses(processIds, sizeof(processIds), &cbNeeded)) { return 0; }
DWORD processCount = cbNeeded / sizeof(DWORD); for (DWORD i = 0; i < processCount; ++i) { if (processIds[i] != 0) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIds[i]); if (hProcess) { HMODULE hMod; DWORD cbNeededModule; WCHAR szProcessName[MAX_PATH]; if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeededModule)) { GetModuleBaseNameW(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(WCHAR)); if (!_wcsicmp(szProcessName, processName.c_str())) { CloseHandle(hProcess); return processIds[i]; } } CloseHandle(hProcess); } } } return 0;}
void DisassembleAndFindHashes(Logger& logger, HANDLE hProcess, uintptr_t baseAddress, SIZE_T size) { std::vector buffer(size); SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, (LPCVOID)baseAddress, buffer.data(), size, &bytesRead)) { logger.Log("Failed to read memory at address 0x" + std::to_string(baseAddress) + ". Error: " + std::to_string(GetLastError()), "ERROR"); return; }
ZydisDecoder decoder; ZydisFormatter formatter; if (ZYAN_FAILED(ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_ADDRESS_WIDTH_64))) { logger.Log("Failed to initialize Zydis decoder", "ERROR"); return; } if (ZYAN_FAILED(ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL))) { logger.Log("Failed to initialize Zydis formatter", "ERROR"); return; } size_t offset = 0; ZydisDecodedInstruction instruction; ZyanU64 runtime_address = baseAddress; while (ZYAN_SUCCESS(ZydisDecoderDecodeBuffer(&decoder, buffer.data() + offset, bytesRead - offset, &instruction))) { char formattedInstruction[256]; if (ZYAN_SUCCESS(ZydisFormatterFormatInstruction(&formatter, &instruction, formattedInstruction, sizeof(formattedInstruction)))) { // Log the instruction with the runtime address logger.Log("0x" + std::to_string(runtime_address) + ": " + std::string(formattedInstruction)); // Simple example: look for calls to `SHA256` or similar (Note: This is illustrative; actual implementation depends on the disassembly) if (std::string(formattedInstruction).find("SHA256") != std::string::npos || std::string(formattedInstruction).find("MD5") != std::string::npos) { logger.Log("Potential Integrity Check at 0x" + std::to_string(runtime_address) + ": " + formattedInstruction, "HASH_CHECK"); } } else { logger.Log("Failed to format instruction at 0x" + std::to_string(runtime_address), "ERROR"); } offset += instruction.length; runtime_address += instruction.length; }}
void AnalyzeModulesForIntegrityChecks(Logger& logger, HANDLE hProcess) { HMODULE hMods[1024]; DWORD cbNeeded; if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (size_t i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { MODULEINFO moduleInfo; if (GetModuleInformation(hProcess, hMods[i], &moduleInfo, sizeof(moduleInfo))) { logger.Log("Analyzing module at Base Address 0x" + std::to_string((uintptr_t)moduleInfo.lpBaseOfDll), "MODULE"); DisassembleAndFindHashes(logger, hProcess, (uintptr_t)moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage); } } } }
int main() { std::wstring processName = L"YourProcess.exe"; // Replace with your process name Logger logger("integrity_log.log");
DWORD pid = GetProcessIdByName(processName); if (pid == 0) { logger.Log("Process not found: " + std::string(processName.begin(), processName.end()), "ERROR"); return 1; } HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (!hProcess) { logger.Log("Failed to open process with PID: " + std::to_string(pid) + ", Error code: " + std::to_string(GetLastError()), "ERROR"); return 1; } AnalyzeModulesForIntegrityChecks(logger, hProcess); CloseHandle(hProcess); return 0;}
- Assistant
Your C++ program is designed to analyze the memory of a specified process, disassemble its modules using the Zydis library, and search for potential integrity checks by looking for calls to hashing functions like
SHA256orMD5. Here's a comprehensive review of your code, including explanations, potential issues, and suggestions for improvements.
Overview of the Code
-
Logger Class:
- Handles logging messages to a specified file.
- Logs include a timestamp and a log level (e.g., INFO, ERROR).
-
Process Identification:
GetProcessIdByName: Retrieves the process ID (PID) of a process given its name.
-
Disassembly and Analysis:
DisassembleAndFindHashes: Disassembles the memory of a module and searches for instructions related to hashing functions.AnalyzeModulesForIntegrityChecks: Enumerates all modules of the target process and invokes the disassembly function on each.
-
Main Function:
- Initializes the logger.
- Retrieves the PID of the target process.
- Opens the process with the necessary permissions.
- Initiates the analysis of modules for integrity checks.
Detailed Review and Suggestions
1. Process Identification with
GetProcessIdByNameCurrent Implementation Issues:
- Case-Insensitive Comparison: You're using
_wcsicmpfor case-insensitive comparison, which is correct. However, ensure that the process name matches exactly, including the.exeextension. - Resource Management: Handles opened with
OpenProcessare appropriately closed in the loop, which is good.
Suggestions:
- Multiple Instances Handling: If multiple instances of the process are running, your function returns the first match. Depending on your use case, you might want to handle multiple instances.
- Enhanced Logging: Log how many processes were enumerated and if multiple matches were found.
Example Enhancement:
std::vector<DWORD> GetProcessIdsByName(const std::wstring& processName) { std::vector<DWORD> matchingPids; // ... (EnumProcesses and comparison logic) return matchingPids; }2. Logging Mechanism
Current Implementation Issues:
- String Conversion: In
main(), you're convertingstd::wstringtostd::stringusingstd::string(processName.begin(), processName.end()), which may lead to data loss ifprocessNamecontains non-ASCII characters. - Address Formatting: Addresses are being converted to strings using
std::to_string, which outputs them in decimal. Typically, memory addresses are represented in hexadecimal for clarity.
Suggestions:
- Use Hexadecimal Formatting: Modify the
Logger::Logfunction or create helper functions to format addresses in hexadecimal. - Unicode Support: Consider handling
std::wstringappropriately to avoid data loss or conversion issues.
Implementation Enhancement:
#include <iomanip> #include <sstream> // Helper function to format addresses in hexadecimal std::string ToHex(uintptr_t address) { std::ostringstream oss; oss << "0x" << std::hex << address; return oss.str(); } // Modify Logger::Log to handle different data types or use helper functions where logging addresses3. Disassembly with Zydis
Current Implementation Issues:
- Instruction Parsing: Searching for strings like
"SHA256"or"MD5"in disassembled instructions assumes that function names are present, which is typically not the case in stripped binaries or without symbol information. - Encoding of Function Calls: Function calls in assembly are usually represented as
CALLinstructions with addresses or relative offsets, not by the function names.
Suggestions:
- Import Table Analysis: Instead of disassembling instructions and searching for function names, analyze the Import Address Table (IAT) to identify imported hashing functions directly.
- Signature-Based Scanning: If looking for inline implementations or dynamically resolved functions (e.g., via
GetProcAddress), consider signature-based scanning or pattern matching.
Implementation Enhancement Example: Import Table Analysis
void AnalyzeImportsForHashes(Logger& logger, HANDLE hProcess, HMODULE hMod, MODULEINFO moduleInfo) { // Read the PE headers and parse the Import Directory // Look for entries corresponding to SHA256, MD5, or other hashing functions // Log any findings }4. Reading Process Memory
Current Implementation Issues:
- Error Logging: When
ReadProcessMemoryfails, you log the base address in decimal, which isn't standard for memory addresses. - Partial Reads: There's no handling for cases where
bytesReadis less thansize. Although unlikely for module memory, it's good practice to handle partial reads.
Suggestions:
- Address Formatting: Use hexadecimal for addresses in error messages.
- Robust Error Handling: Implement retry mechanisms or more descriptive error messages.
Implementation Enhancement:
// Replace the following line logger.Log("Failed to read memory at address 0x" + std::to_string(baseAddress) + ". Error: " + std::to_string(GetLastError()), "ERROR"); // With logger.Log("Failed to read memory at address " + ToHex(baseAddress) + ". Error: " + std::to_string(GetLastError()), "ERROR");5. Module Analysis
Current Implementation Issues:
- Logging Base Address: Similar to previous points, the base address is logged in decimal.
- Module Size Assumptions: The code assumes that
moduleInfo.SizeOfImageaccurately reflects the readable memory size, which is usually true but can vary.
Suggestions:
- Hexadecimal Formatting: Log addresses in hexadecimal.
- Selective Module Analysis: Depending on your goals, you might want to exclude system modules or focus on specific types of modules.
6. General Recommendations
- Permissions: Ensure the program runs with sufficient privileges (e.g., Administrator) to read other processes' memory.
- Error Checking: While you've implemented some error checks, consider adding more detailed error handling and logging for different failure points.
- Performance Considerations: Disassembling large modules can be time-consuming. Implement progress logging or optimizations if needed.
- Thread Safety: If you plan to extend the program for multi-threaded analysis, ensure the logger and other shared resources are thread-safe.
Revised Code with Enhancements
Below is an improved version of your code incorporating some of the suggestions:
#include <iostream> #include <windows.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <sstream> #include <ctime> #include <Zydis/Zydis.h> #include <iomanip> // Ensure that you have the correct library linkage #pragma comment(lib, "psapi.lib") class Logger { public: explicit Logger(const std::string& filepath) : logFilePath(filepath) { InitLog(); } void Log(const std::string& message, const std::string& level = "INFO") { std::ofstream logFile(logFilePath, std::ios::app); if (logFile.is_open()) { logFile << "[" << GetFormattedTime() << "] [" << level << "] " << message << "\n"; } } private: std::string logFilePath; void InitLog() { std::ofstream logFile(logFilePath, std::ios::trunc); if (logFile.is_open()) { logFile << "[" << GetFormattedTime() << "] [INIT] Log initiated\n"; } } std::string GetFormattedTime() { std::time_t currentTime = std::time(nullptr); char buffer[100]; struct tm timeInfo; localtime_s(&timeInfo, ¤tTime); std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &timeInfo); return std::string(buffer); } }; // Helper function to format addresses in hexadecimal std::string ToHex(uintptr_t address) { std::ostringstream oss; oss << "0x" << std::hex << address; return oss.str(); } DWORD GetProcessIdByName(const std::wstring& processName) { DWORD processIds[1024], cbNeeded; if (!EnumProcesses(processIds, sizeof(processIds), &cbNeeded)) { return 0; } DWORD processCount = cbNeeded / sizeof(DWORD); for (DWORD i = 0; i < processCount; ++i) { if (processIds[i] != 0) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIds[i]); if (hProcess) { HMODULE hMod; DWORD cbNeededModule; WCHAR szProcessName[MAX_PATH]; if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeededModule)) { if (GetModuleBaseNameW(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(WCHAR))) { if (!_wcsicmp(szProcessName, processName.c_str())) { CloseHandle(hProcess); return processIds[i]; } } } CloseHandle(hProcess); } } } return 0; } void DisassembleAndFindHashes(Logger& logger, HANDLE hProcess, uintptr_t baseAddress, SIZE_T size) { std::vector<BYTE> buffer(size); SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, (LPCVOID)baseAddress, buffer.data(), size, &bytesRead)) { logger.Log("Failed to read memory at address " + ToHex(baseAddress) + ". Error: " + std::to_string(GetLastError()), "ERROR"); return; } ZydisDecoder decoder; ZydisFormatter formatter; if (ZYAN_FAILED(ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_ADDRESS_WIDTH_64))) { logger.Log("Failed to initialize Zydis decoder", "ERROR"); return; } if (ZYAN_FAILED(ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL))) { logger.Log("Failed to initialize Zydis formatter", "ERROR"); return; } size_t offset = 0; ZydisDecodedInstruction instruction; ZyanU64 runtime_address = baseAddress; while (ZYAN_SUCCESS(ZydisDecoderDecodeBuffer(&decoder, buffer.data() + offset, bytesRead - offset, &instruction))) { char formattedInstruction[256]; if (ZYAN_SUCCESS(ZydisFormatterFormatInstruction(&formatter, &instruction, formattedInstruction, sizeof(formattedInstruction)))) { // Log the instruction with the runtime address logger.Log(ToHex(runtime_address) + ": " + std::string(formattedInstruction)); // Simple example: look for calls to `SHA256` or `MD5` (Note: This is illustrative; actual implementation depends on the disassembly) if (instruction.mnemonic == ZYDIS_MNEMONIC_CALL) { // Potentially, analyze the operands to determine if it's a call to a hashing function // This requires further implementation based on how functions are called // For now, this is a placeholder } } else { logger.Log("Failed to format instruction at " + ToHex(runtime_address), "ERROR"); } offset += instruction.length; runtime_address += instruction.length; } } void AnalyzeModulesForIntegrityChecks(Logger& logger, HANDLE hProcess) { HMODULE hMods[1024]; DWORD cbNeeded; if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { size_t moduleCount = cbNeeded / sizeof(HMODULE); logger.Log("Number of modules found: " + std::to_string(moduleCount)); for (size_t i = 0; i < moduleCount; i++) { MODULEINFO moduleInfo; if (GetModuleInformation(hProcess, hMods[i], &moduleInfo, sizeof(moduleInfo))) { uintptr_t baseAddr = reinterpret_cast<uintptr_t>(moduleInfo.lpBaseOfDll); logger.Log("Analyzing module " + std::to_string(i + 1) + " at Base Address " + ToHex(baseAddr), "MODULE"); DisassembleAndFindHashes(logger, hProcess, baseAddr, moduleInfo.SizeOfImage); } else { logger.Log("Failed to get information for module " + std::to_string(i + 1), "ERROR"); } } } else { logger.Log("Failed to enumerate process modules. Error code: " + std::to_string(GetLastError()), "ERROR"); } } int main() { std::wstring processName = L"YourProcess.exe"; // Replace with your process name Logger logger("integrity_log.log"); DWORD pid = GetProcessIdByName(processName); if (pid == 0) { // Convert wide string to narrow string safely for logging std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::string processNameStr = converter.to_bytes(processName); logger.Log("Process not found: " + processNameStr, "ERROR"); return 1; } logger.Log("Found process " + std::to_string(pid) + ": " + ToHex(pid), "INFO"); HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (!hProcess) { logger.Log("Failed to open process with PID: " + std::to_string(pid) + ", Error code: " + std::to_string(GetLastError()), "ERROR"); return 1; } AnalyzeModulesForIntegrityChecks(logger, hProcess); CloseHandle(hProcess); return 0; }Key Enhancements:
-
Hexadecimal Address Formatting:
- Added the
ToHexhelper function to format addresses properly. - Updated log messages to use hexadecimal formatting for addresses.
- Added the
-
Improved Logging:
- Added more detailed logs, such as the number of modules found.
- Ensured that logs handle wide strings correctly using
std::wstring_convert.
-
Placeholder for Call Analysis:
- In
DisassembleAndFindHashes, added a placeholder to handleCALLinstructions. To effectively identify calls to hashing functions, further implementation is needed, potentially analyzing the targets ofCALLinstructions.
- In
-
Error Handling:
- Enhanced error messages with more context.
- Added checks and logs for failures in retrieving module information.
-
Unicode Handling:
- Used
std::wstring_convertto safely convertstd::wstringtostd::stringfor logging.
- Used
Further Improvements and Considerations
1. Import Table Analysis vs. Disassembly
While disassembling code to find hashing function calls can be insightful, analyzing the Import Address Table (IAT) is often more straightforward and reliable for identifying imported functions.
Advantages of Import Table Analysis:
- Simplicity: Direct access to imported function names without parsing assembly.
- Performance: Faster than decoding and analyzing every instruction.
- Accuracy: Reduces false positives that might occur when parsing assembly instructions.
Implementation Tip: Use
ImageImportDescriptorstructures to iterate over imported modules and their functions, checking for known hashing functions.2. Handling Inline or Dynamically Resolved Functions
If a process uses hashing functions not directly imported (e.g., dynamically via
GetProcAddressor inline implementations), more sophisticated techniques are required:- Pattern Matching: Use byte pattern scans to identify common hashing function signatures.
- Heuristics: Analyze control flow or data usage patterns indicative of hashing operations.
- Function Hooking: Monitor calls to external hashing APIs in real-time (advanced and may require separate considerations).
3. Multi-threaded Analysis
For large processes with numerous modules, consider parallelizing the module analysis to improve performance.
Implementation Tip: Utilize C++ threading libraries (e.g.,
std::thread,std::async) to process multiple modules concurrently, ensuring thread-safe operations in the logger.4. User Interface Enhancements
For better usability, consider adding:
- Command-Line Arguments: Allow specifying the target process name and log file path via command-line.
- Progress Indicators: Inform the user about ongoing analysis progress.
- Summary Reports: Generate a summary after analysis, highlighting any potential integrity checks found.
5. Security and Permissions
- Running with Sufficient Privileges: Ensure the tool is executed with the necessary permissions to access other processes' memory.
- Anti-Debugging Measures: Be aware that some processes might employ techniques to prevent inspection, which could lead to access issues or incomplete analysis.
Conclusion
Your program lays a solid foundation for process memory analysis and integrity check detection. By implementing the suggested enhancements, particularly focusing on accurate detection methods (like import table analysis), improving logging mechanisms, and ensuring robust error handling, you can significantly enhance the reliability and effectiveness of your tool.
Remember to handle edge cases, such as multiple process instances and dynamically loaded functions, to make your analysis comprehensive. Additionally, always ensure that you have the legal and ethical right to inspect and analyze other processes, as unauthorized access can lead to violations of privacy and security policies.
If you have specific questions or encounter issues while implementing these suggestions, feel free to ask!
-