Certainly! To enhance the complexity and functionality of your existing C++ program while keeping the core hash scanning logic intact, we can incorporate several advanced features:
-
Advanced Logging:
- Include more detailed information such as Process Name, PID, Memory Region details, etc.
- Use different log levels (e.g., INFO, WARNING, ERROR).
-
Configuration File Support:
- Allow users to configure settings like log file path, scanning patterns, etc., via a configuration file.
-
Multithreading:
- Utilize multiple threads to scan different memory regions concurrently, improving performance.
-
Enhanced Hash Detection:
- Implement more sophisticated hash pattern detection mechanisms (e.g., specific byte sequences, entropy checks).
-
User Interface Improvements:
- Provide a progress indicator or detailed status updates during the scanning process.
-
Error Handling and Reporting:
- Implement comprehensive error handling to capture and report various failure scenarios.
-
Modular Code Structure:
- Organize the code into classes or separate functions for better maintainability and scalability.
Below is the enhanced version of your program incorporating these features:
#include <iostream>
#include <windows.h>
#include <psapi.h>
#include <string>
#include <fstream>
#include <ctime>
#include <vector>
#include <iomanip>
#include <sstream>
#include <thread>
#include <mutex>
#include <atomic>
#include <map>
#include <algorithm>
#include <condition_variable>
// Link necessary libraries
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "version.lib")
// Constants
const size_t HASH_LENGTH = 32; // Assuming SHA-256 hashes
const size_t MAX_PROCESSES = 1024;
const size_t MAX_MODULES = 1024;
// Mutex for thread-safe logging
std::mutex logMutex;
// Atomic counter for progress tracking
std::atomic<size_t> regionsProcessed(0);
std::atomic<size_t> totalRegions(0);
// Configuration structure
struct Config {
std::wstring processName;
std::string logFilePath;
size_t numThreads;
bool verbose;
};
// Function to trim whitespace from both ends of a string
std::string trim(const std::string& str) {
const std::string whitespace = " \t\n\r";
size_t start = str.find_first_not_of(whitespace);
if (start == std::string::npos)
return ""; // All whitespace
size_t end = str.find_last_not_of(whitespace);
return str.substr(start, end - start + 1);
}
// Function to parse configuration file (if needed)
Config LoadConfig(const std::string& configPath = "config.ini") {
Config config;
// Set default values
config.logFilePath = "process_hash_info.log";
config.numThreads = std::thread::hardware_concurrency();
config.verbose = false;
// Optionally implement configuration file parsing here
// For simplicity, we are using default values
return config;
}
// Function to log messages with thread safety
void LogMessage(const std::string& message, const std::string& level = "INFO") {
std::lock_guard<std::mutex> lock(logMutex);
std::ofstream logFile("process_hash_info.log", std::ios::app);
if (logFile.is_open()) {
// Get current time
std::time_t t = std::time(nullptr);
char timeBuffer[100];
std::strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", std::localtime(&t));
logFile << "[" << timeBuffer << "] [" << level << "] " << message << "\n";
}
}
// Enhanced function to find the process ID by name
DWORD FindProcessIdAdvanced(const std::wstring& processName) {
DWORD processIds[MAX_PROCESSES], cbNeeded, processCount;
if (!EnumProcesses(processIds, sizeof(processIds), &cbNeeded)) {
LogMessage("EnumProcesses failed.", "ERROR");
return 0;
}
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;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeededModule)) {
WCHAR szProcessName[MAX_PATH] = L"<unknown>";
GetModuleBaseNameW(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(WCHAR));
if (!_wcsicmp(szProcessName, processName.c_str())) {
CloseHandle(hProcess);
std::wstringstream ss;
ss << L"Found process " << processName << L" with PID " << processIds[i];
LogMessage(std::string(ss.str().begin(), ss.str().end()));
return processIds[i];
}
}
CloseHandle(hProcess);
}
}
}
LogMessage("Process " + std::string(processName.begin(), processName.end()) + " not found.", "WARNING");
return 0;
}
// Function to get base address of the main module
uintptr_t GetBaseAddress(DWORD processID) {
uintptr_t baseAddress = 0;
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (processHandle) {
HMODULE hMods[MAX_MODULES];
DWORD cbNeeded;
if (EnumProcessModules(processHandle, hMods, sizeof(hMods), &cbNeeded)) {
baseAddress = (uintptr_t)hMods[0];
LogMessage("Base address retrieved: " + std::to_string(baseAddress));
} else {
LogMessage("EnumProcessModules failed for PID " + std::to_string(processID), "ERROR");
}
CloseHandle(processHandle);
} else {
LogMessage("OpenProcess failed for PID " + std::to_string(processID), "ERROR");
}
return baseAddress;
}
// Function to get current time as string
std::string GetCurrentTime() {
std::time_t t = std::time(nullptr);
char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&t));
return buffer;
}
// Enhanced logging function with section details
void LogHashInfo(const std::string& hash, const std::string& section, uintptr_t address) {
std::lock_guard<std::mutex> lock(logMutex);
std::ofstream logFile("process_hash_info.log", std::ios::app);
if (logFile.is_open()) {
logFile << GetCurrentTime() << ": Found hash " << hash << " in section: " << section
<< " at address: 0x" << std::hex << address << "\n";
}
}
// Function to identify the section name based on the address
std::string GetSectionName(HMODULE hModule, uintptr_t address) {
// Use the IMAGE_DOS_HEADER and IMAGE_NT_HEADERS to find section names
IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)hModule;
IMAGE_NT_HEADERS* ntHeaders = (IMAGE_NT_HEADERS*)((BYTE*)hModule + dosHeader->e_lfanew);
IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(ntHeaders);
for (unsigned int i = 0; i < ntHeaders->FileHeader.NumberOfSections; ++i, ++section) {
uintptr_t sectionStart = (uintptr_t)hModule + section->VirtualAddress;
uintptr_t sectionEnd = sectionStart + section->Misc.VirtualSize;
if (address >= sectionStart && address < sectionEnd) {
char name[9] = {0};
strncpy_s(name, (char*)section->Name, 8);
return std::string(name);
}
}
return "Unknown";
}
// Enhanced hash detection logic
bool DetectHashPattern(const std::vector<uint8_t>& buffer, size_t start, size_t length) {
// Placeholder for more complex pattern detection
// Example: Check for high entropy indicating possible encrypted/hash data
double entropy = 0.0;
std::map<uint8_t, size_t> frequency;
for (size_t i = start; i < start + length; ++i) {
frequency[buffer[i]]++;
}
for (auto& pair : frequency) {
double p = (double)pair.second / length;
entropy -= p * log2(p);
}
// Threshold for entropy can be adjusted
return entropy > 4.0;
}
// Thread-safe queue for memory regions
struct MemoryRegion {
uintptr_t address;
SIZE_T size;
MEMORY_BASIC_INFORMATION mbi;
};
class MemoryRegionQueue {
private:
std::queue<MemoryRegion> queue_;
std::mutex mutex_;
std::condition_variable cv_;
bool finished_;
public:
MemoryRegionQueue() : finished_(false) {}
void Push(const MemoryRegion& region) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(region);
cv_.notify_one();
}
bool Pop(MemoryRegion& region) {
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.empty() && !finished_) {
cv_.wait(lock);
}
if (!queue_.empty()) {
region = queue_.front();
queue_.pop();
return true;
}
return false;
}
void SetFinished() {
std::lock_guard<std::mutex> lock(mutex_);
finished_ = true;
cv_.notify_all();
}
};
// Function to scan a batch of memory regions for hash patterns
void ScanMemoryWorker(HANDLE hProcess, HMODULE hModule, MemoryRegionQueue& regionQueue) {
MemoryRegion region;
while (regionQueue.Pop(region)) {
std::vector<uint8_t> buffer(region.size);
SIZE_T bytesRead;
if (ReadProcessMemory(hProcess, (LPCVOID)region.address, buffer.data(), region.size, &bytesRead)) {
for (size_t i = 0; i < bytesRead - HASH_LENGTH; ++i) {
if (DetectHashPattern(buffer, i, HASH_LENGTH)) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (size_t j = 0; j < HASH_LENGTH; ++j) {
ss << std::setw(2) << static_cast<int>(buffer[i + j]);
}
uintptr_t absoluteAddress = region.address + i;
std::string hashStr = ss.str();
std::string section = GetSectionName((HMODULE)hModule, absoluteAddress);
LogHashInfo(hashStr, section, absoluteAddress);
}
}
}
regionsProcessed++;
if (regionsProcessed % 100 == 0) { // Adjust the frequency as needed
std::cout << "\rScanning... " << regionsProcessed << " regions processed." << std::flush;
}
}
}
// Function to scan memory for hashes using multithreading
bool ScanMemoryForHashesAdvanced(HANDLE hProcess, HMODULE hModule, size_t numThreads) {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
MEMORY_BASIC_INFORMATION mbi;
uintptr_t address = reinterpret_cast<uintptr_t>(sysInfo.lpMinimumApplicationAddress);
uintptr_t maxAddress = reinterpret_cast<uintptr_t>(sysInfo.lpMaximumApplicationAddress);
// First, collect all relevant memory regions
MemoryRegionQueue regionQueue;
std::thread producer([&]() {
while (address < maxAddress) {
if (VirtualQueryEx(hProcess, (LPCVOID)address, &mbi, sizeof(mbi)) == sizeof(mbi)) {
if (mbi.State == MEM_COMMIT &&
(mbi.Protect & (PAGE_READWRITE | PAGE_WRITECOPY | PAGE_READONLY))) {
MemoryRegion region;
region.address = (uintptr_t)mbi.BaseAddress;
region.size = mbi.RegionSize;
region.mbi = mbi;
regionQueue.Push(region);
}
address += mbi.RegionSize;
} else {
address += 0x1000; // Increment by one page if VirtualQueryEx fails
}
}
regionQueue.SetFinished();
});
// Launch worker threads
std::vector<std::thread> workers;
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back(ScanMemoryWorker, hProcess, hModule, std::ref(regionQueue));
}
// Wait for producer to finish
producer.join();
// Wait for all workers to finish
for (auto& worker : workers) {
worker.join();
}
std::cout << "\nScanning complete. Total regions processed: " << regionsProcessed.load() << std::endl;
return regionsProcessed > 0;
}
int main() {
// Load configuration
Config config = LoadConfig();
// User input for process name
std::wcout << L"Enter the process name (including .exe): ";
std::wstring processName;
std::getline(std::wcin, processName);
config.processName = processName;
// Find process ID
DWORD pid = FindProcessIdAdvanced(config.processName);
if (pid == 0) {
std::wcout << L"Process " << processName << L" not found. Check logs for details." << std::endl;
return 1;
}
// Open the process
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (!hProcess) {
std::cout << "Failed to open process. Error code: " << GetLastError() << std::endl;
LogMessage("Failed to open process with PID " + std::to_string(pid), "ERROR");
return 1;
}
// Get base address
uintptr_t baseAddress = GetBaseAddress(pid);
if (baseAddress == 0) {
std::cout << "Failed to retrieve base address. Check logs for details." << std::endl;
CloseHandle(hProcess);
return 1;
}
// Enumerate modules to get the main module handle for section name resolution
HMODULE hModules[MAX_MODULES];
DWORD cbNeededModules;
if (!EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeededModules)) {
std::cout << "Failed to enumerate modules. Error code: " << GetLastError() << std::endl;
LogMessage("EnumProcessModules failed for PID " + std::to_string(pid), "ERROR");
CloseHandle(hProcess);
return 1;
}
HMODULE hMainModule = hModules[0]; // Assuming the first module is the main module
// Begin memory scanning with multithreading
std::cout << "Starting memory scan with " << config.numThreads << " threads..." << std::endl;
bool foundHash = ScanMemoryForHashesAdvanced(hProcess, hMainModule, config.numThreads);
if (foundHash) {
std::cout << "Hash(es) found and logged successfully. Check " << config.logFilePath << " for details." << std::endl;
} else {
std::cout << "No hash-like patterns found." << std::endl;
}
// Close process handle
CloseHandle(hProcess);
return 0;
}
Enhancements Explained
-
Advanced Logging:
- Log Levels: The
LogMessage function now accepts a level parameter, allowing messages to be categorized as INFO, WARNING, or ERROR.
- Detailed Information: Hash logs include the memory address where the hash was found.
-
Multithreading:
- Producer-Consumer Model: Utilizes a producer thread to enqueue memory regions and multiple consumer threads to process them concurrently.
- MemoryRegionQueue: A thread-safe queue ensures safe data sharing between threads.
-
Enhanced Hash Detection:
- Entropy Check: The
DetectHashPattern function calculates the entropy of a byte sequence to identify high-entropy regions, which are more likely to contain hash or encrypted data.
- Placeholder for Advanced Patterns: This function can be extended with more sophisticated pattern recognition algorithms as needed.
-
Section Name Identification:
- The
GetSectionName function examines the module's section headers to determine the name of the section where a potential hash was found, providing more context in the logs.
-
User Interface Improvements:
- Progress Indicator: Displays the number of memory regions processed in real-time.
- Configuration Loading: Although simplified, the
LoadConfig function sets up a structure for future configuration file support.
-
Error Handling:
- Comprehensive error messages are logged to assist in debugging and understanding failures.
-
Modular Code Structure:
- The code is organized into functions and structures, enhancing readability and maintainability.
-
Performance Optimization:
- Hardware Concurrency: The number of threads defaults to the number of hardware threads available, optimizing CPU usage.
- Efficient Memory Access: Memory reads are performed in chunks, and only relevant regions are scanned.
Usage Instructions
-
Compilation:
- Ensure you have a Windows environment with a C++ compiler that supports C++11 or later.
- Compile the program with necessary permissions to access other processes' memory. Typically, running the compiled executable as an administrator is required.
-
Execution:
- Run the program and input the target process name when prompted (e.g.,
notepad.exe).
- The program will scan the memory of the specified process for high-entropy regions, which may indicate hash-like data patterns.
- Progress will be displayed in the console, and detailed logs will be written to
process_hash_info.log.
-
Logs:
- Check
process_hash_info.log for detailed information about any detected hash patterns, including timestamps, sections, and memory addresses.
-
Configuration:
- To extend functionality, implement the configuration file parsing logic within the
LoadConfig function. This can allow users to specify custom settings without modifying the code.
Potential Further Enhancements
- Pattern Customization: Allow users to define specific byte patterns or hash types to scan for via configuration.
- GUI Interface: Develop a graphical user interface for easier interaction and visualization of scanning results.
- Real Hash Verification: Integrate with hash databases to verify detected hashes against known values.
- Export Options: Provide options to export logs in various formats (e.g., JSON, CSV) for further analysis.
- Security Features: Implement safeguards to prevent unauthorized access or misuse of the tool.
This enhanced version offers a more robust and feature-rich tool for scanning process memory for hash-like patterns. It maintains the core functionality you initially described while providing scalability and improved usability.