study this then rewrite it ground up using non of the code from this it should new type of functionality ensure there is no erros #include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include
#include
#include
#include
#include
// Constants
const uintptr_t OFFSET_ADJUSTMENT = 0x10; // Adjust based on analysis
// Function to log messages to console and optionally to a file
void log_message(FILE* log_file, bool log_to_file, const char* format, ...) {
va_list args;
va_start(args, format);
code
// Output to console
vprintf(format, args);
if (log_to_file && log_file != NULL) {
// Make a copy of args for file logging
va_list args_copy;
va_copy(args_copy, args);
vfprintf(log_file, format, args_copy);
va_end(args_copy);
fflush(log_file);
}
va_end(args);
}
// Function to get the Process ID (PID) by process name
DWORD get_process_id_by_name(const char* process_name, FILE* log_file) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
code
if (hSnapshot == INVALID_HANDLE_VALUE) {
log_message(log_file, false, "Error: Unable to create tool help snapshot. Error Code: %lu\n", GetLastError());
return 0;
}
if (!Process32First(hSnapshot, &pe32)) {
log_message(log_file, false, "Error: Unable to retrieve information on the first process. Error Code: %lu\n", GetLastError());
CloseHandle(hSnapshot);
return 0;
}
do {
// Convert wide string to ANSI
char exeFile[MAX_PATH];
size_t converted_chars = 0;
wcstombs_s(&converted_chars, exeFile, MAX_PATH, pe32.szExeFile, _TRUNCATE);
if (_stricmp(exeFile, process_name) == 0) {
CloseHandle(hSnapshot);
log_message(log_file, false, "Process '%s' found with PID %u\n", process_name, pe32.th32ProcessID);
return pe32.th32ProcessID;
}
} while (Process32Next(hSnapshot, &pe32));
CloseHandle(hSnapshot);
log_message(log_file, false, "Error: Process '%s' not found\n", process_name);
return 0;
Assistant
}
// Function to get the base address of the main module (e.g., Fallout76.exe)
unsigned long long get_base_address(DWORD pid, FILE* log_file) {
MODULEENTRY32 me32;
me32.dwSize = sizeof(MODULEENTRY32);
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
code
if (hSnapshot == INVALID_HANDLE_VALUE) {
log_message(log_file, false, "Error: Unable to create module snapshot. Error Code: %lu\n", GetLastError());
return 0;
}
if (!Module32First(hSnapshot, &me32)) {
log_message(log_file, false, "Error: Unable to retrieve information on the first module. Error Code: %lu\n", GetLastError());
CloseHandle(hSnapshot);
return 0;
}
unsigned long long base_address = (unsigned long long)(uintptr_t)me32.modBaseAddr;
CloseHandle(hSnapshot);
log_message(log_file, false, "Base address of the main module: 0x%llx\n", base_address);
return base_address;
}
// Function to get the start and end addresses of a specific section (e.g., .data or .rdata)
bool get_section_limits(HANDLE hProcess, unsigned long long base_addr, const char* section_name, unsigned long long& section_start, unsigned long long& section_end) {
IMAGE_DOS_HEADER dos_header;
if (!ReadProcessMemory(hProcess, (LPCVOID)base_addr, &dos_header, sizeof(dos_header), NULL)) {
return false;
}
code
if (dos_header.e_magic != IMAGE_DOS_SIGNATURE) {
return false;
}
IMAGE_NT_HEADERS32 nt_headers32;
IMAGE_NT_HEADERS64 nt_headers64;
BOOL is64Bit = FALSE;
// Read the magic number to determine 32 or 64 bit
WORD magic;
if (!ReadProcessMemory(hProcess, (LPCVOID)(base_addr + dos_header.e_lfanew + offsetof(IMAGE_NT_HEADERS, OptionalHeader)), &magic, sizeof(magic), NULL)) {
return false;
}
if (magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
is64Bit = TRUE;
// Read entire IMAGE_NT_HEADERS64
if (!ReadProcessMemory(hProcess, (LPCVOID)(base_addr + dos_header.e_lfanew), &nt_headers64, sizeof(nt_headers64), NULL)) {
return false;
}
// Allocate memory for section headers
std::unique_ptr<IMAGE_SECTION_HEADER[]> section_headers(new IMAGE_SECTION_HEADER[nt_headers64.FileHeader.NumberOfSections]);
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(
hProcess,
(LPCVOID)(base_addr + dos_header.e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER64)),
section_headers.get(),
sizeof(IMAGE_SECTION_HEADER) * nt_headers64.FileHeader.NumberOfSections,
&bytes_read) || bytes_read != sizeof(IMAGE_SECTION_HEADER) * nt_headers64.FileHeader.NumberOfSections) {
return false;
}
// Iterate through sections to find the desired one
for (unsigned int i = 0; i < nt_headers64.FileHeader.NumberOfSections; ++i) {
if (strncmp((char*)section_headers[i].Name, section_name, IMAGE_SIZEOF_SHORT_NAME) == 0) {
section_start = base_addr + section_headers[i].VirtualAddress;
section_end = section_start + section_headers[i].Misc.VirtualSize;
return true;
}
}
}
else if (magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
is64Bit = FALSE;
// Read entire IMAGE_NT_HEADERS32
if (!ReadProcessMemory(hProcess, (LPCVOID)(base_addr + dos_header.e_lfanew), &nt_headers32, sizeof(nt_headers32), NULL)) {
return false;
}
// Allocate memory for section headers
std::unique_ptr<IMAGE_SECTION_HEADER[]> section_headers(new IMAGE_SECTION_HEADER[nt_headers32.FileHeader.NumberOfSections]);
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(
hProcess,
(LPCVOID)(base_addr + dos_header.e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER32)),
section_headers.get(),
sizeof(IMAGE_SECTION_HEADER) * nt_headers32.FileHeader.NumberOfSections,
&bytes_read) || bytes_read != sizeof(IMAGE_SECTION_HEADER) * nt_headers32.FileHeader.NumberOfSections) {
return false;
}
// Iterate through sections to find the desired one
for (unsigned int i = 0; i < nt_headers32.FileHeader.NumberOfSections; ++i) {
if (strncmp((char*)section_headers[i].Name, section_name, IMAGE_SIZEOF_SHORT_NAME) == 0) {
section_start = base_addr + section_headers[i].VirtualAddress;
section_end = section_start + section_headers[i].Misc.VirtualSize;
return true;
}
}
}
else {
return false; // Unknown format
}
return false; // Section not found
}
// Function to find the address of a given ANSI string within a memory section
unsigned long long find_string_in_section(HANDLE hProcess, unsigned long long section_start, unsigned long long section_end, const std::string& target_string, FILE* log_file) {
SIZE_T section_size = section_end - section_start;
std::unique_ptr<BYTE[]> buffer(new BYTE[section_size]);
SIZE_T bytes_read = 0;
code
// Read the entire section into the buffer
if (!ReadProcessMemory(hProcess, (LPCVOID)section_start, buffer.get(), section_size, &bytes_read)) {
log_message(log_file, false, "Error: Unable to read memory section at 0x%llx\n", section_start);
return 0;
}
if (bytes_read < section_size) {
log_message(log_file, false, "Warning: Read fewer bytes (%llu) than expected (%llu)\n", bytes_read, section_size);
}
// Search for the target string within the buffer
for (SIZE_T i = 0; i <= bytes_read - target_string.length(); ++i) {
if (memcmp(buffer.get() + i, target_string.c_str(), target_string.length()) == 0) {
// Ensure the string is null-terminated
if (i + target_string.length() < bytes_read && buffer[i + target_string.length()] == '\0') {
unsigned long long string_addr = section_start + i;
log_message(log_file, false, "Found string '%s' at address 0x%llx\n", target_string.c_str(), string_addr);
return string_addr;
}
}
}
log_message(log_file, false, "String '%s' not found in section 0x%llx - 0x%llx\n", target_string.c_str(), section_start, section_end);
return 0;
}
// Function to find the address that references a given string address (i.e., where a pointer points to string_addr)
unsigned long long find_pointer_to_address(HANDLE hProcess, unsigned long long section_start, unsigned long long section_end, unsigned long long target_address, bool is64Bit, FILE* log_file) {
SIZE_T pointer_size = is64Bit ? sizeof(unsigned long long) : sizeof(unsigned long);
SIZE_T section_size = section_end - section_start;
std::unique_ptr<BYTE[]> buffer(new BYTE[section_size]);
SIZE_T bytes_read = 0;
code
// Read the entire section into the buffer
if (!ReadProcessMemory(hProcess, (LPCVOID)section_start, buffer.get(), section_size, &bytes_read)) {
log_message(log_file, false, "Error: Unable to read memory section at 0x%llx\n", section_start);
return 0;
}
if (bytes_read < section_size) {
log_message(log_file, false, "Warning: Read fewer bytes (%llu) than expected (%llu)\n", bytes_read, section_size);
}
// Iterate through the buffer to find instances of target_address
for (SIZE_T i = 0; i <= bytes_read - pointer_size; ++i) {
unsigned long long potential_ptr = 0;
if (is64Bit) {
memcpy(&potential_ptr, buffer.get() + i, sizeof(unsigned long long));
}
else {
unsigned long temp_ptr = 0;
memcpy(&temp_ptr, buffer.get() + i, sizeof(unsigned long));
potential_ptr = static_cast<unsigned long long>(temp_ptr);
}
if (potential_ptr == target_address) {
unsigned long long pointer_addr = section_start + i;
log_message(log_file, false, "Found pointer to address 0x%llx at 0x%llx\n", target_address, pointer_addr);
return pointer_addr;
}
}
log_message(log_file, false, "Pointer to address 0x%llx not found in section 0x%llx - 0x%llx\n", target_address, section_start, section_end);
return 0;
// Open log file
FILE* log_file;
if (fopen_s(&log_file, "memscan.log", "w") != 0) {
printf("Could not open log file for writing\n");
return 1;
}
// Log start time
time_t t = time(NULL);
struct tm tm_info;
if (localtime_s(&tm_info, &t) != 0) {
log_message(log_file, false, "Error: Could not get local time.\n");
fclose(log_file);
return 1;
}
log_message(log_file, true, "Memory scan started at: %04d-%02d-%02d %02d:%02d:%02d\n",
tm_info.tm_year + 1900, tm_info.tm_mon + 1, tm_info.tm_mday,
tm_info.tm_hour, tm_info.tm_min, tm_info.tm_sec);
// Get Process ID
DWORD pid = get_process_id_by_name(process_name, log_file);
if (pid == 0) {
log_message(log_file, true, "Exiting program.\n");
fclose(log_file);
return 1;
}
// Get Base Address
unsigned long long base_addr = get_base_address(pid, log_file);
if (base_addr == 0) {
log_message(log_file, true, "Exiting program.\n");
fclose(log_file);
return 1;
}
// Open Process with necessary permissions
HANDLE hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess == NULL) {
log_message(log_file, true, "Error: Could not open process %d. Error Code: %lu\n", pid, GetLastError());
fclose(log_file);
return 1;
}
// Determine if the process is 64-bit or 32-bit
BOOL isWow64 = FALSE;
if (!IsWow64Process(hProcess, &isWow64)) {
log_message(log_file, true, "Error: Unable to determine process architecture. Error Code: %lu\n", GetLastError());
CloseHandle(hProcess);
fclose(log_file);
return 1;
}
BOOL is64Bit = FALSE;
SYSTEM_INFO systemInfo;
GetNativeSystemInfo(&systemInfo);
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64) {
is64Bit = !isWow64;
}
log_message(log_file, true, "Target process is %s-bit.\n", is64Bit ? "64" : "32");
// Get .data section limits
unsigned long long data_start, data_end;
if (!get_section_limits(hProcess, base_addr, ".data", data_start, data_end)) {
log_message(log_file, true, "Error: Could not find .data section.\n");
CloseHandle(hProcess);
fclose(log_file);
return 1;
}
log_message(log_file, true, ".data section: Start = 0x%llx, End = 0x%llx\n", data_start, data_end);
// Get .rdata section limits
unsigned long long rdata_start, rdata_end;
if (!get_section_limits(hProcess, base_addr, ".rdata", rdata_start, rdata_end)) {
log_message(log_file, true, "Error: Could not find .rdata section.\n");
CloseHandle(hProcess);
fclose(log_file);
return 1;
}
log_message(log_file, true, ".rdata section: Start = 0x%llx, End = 0x%llx\n", rdata_start, rdata_end);
// Begin logging results
fprintf(log_file, "\n$gameSettings = {\n");
// Iterate through each string in gameSettings
for (const auto& setting : gameSettings) {
log_message(log_file, true, "\nProcessing string: '%s'\n", setting.c_str());
// Step 1: Search for the string in .data and .rdata sections
unsigned long long string_addr = 0;
// Search in .data
string_addr = find_string_in_section(hProcess, data_start, data_end, setting, log_file);
// If not found in .data, search in .rdata
if (string_addr == 0) {
string_addr = find_string_in_section(hProcess, rdata_start, rdata_end, setting, log_file);
}
if (string_addr == 0) {
log_message(log_file, true, "Error: String '%s' not found in any section.\n", setting.c_str());
continue;
}
// Step 2: Search for references (pointers) to string_addr in .data and .rdata sections
unsigned long long load_addr = 0;
// Search in .data
load_addr = find_pointer_to_address(hProcess, data_start, data_end, string_addr, is64Bit, log_file);
// If not found in .data, search in .rdata
if (load_addr == 0) {
load_addr = find_pointer_to_address(hProcess, rdata_start, rdata_end, string_addr, is64Bit, log_file);
}
if (load_addr == 0) {
log_message(log_file, true, "Error: Reference to string '%s' not found.\n", setting.c_str());
continue;
}
// Step 3: Calculate function pointer by subtracting OFFSET_ADJUSTMENT
unsigned long long func_ptr = load_addr - OFFSET_ADJUSTMENT;
log_message(log_file, true, "Function pointer for '%s': 0x%llx\n", setting.c_str(), func_ptr);
// Step 4: Calculate offset relative to base address
unsigned long long offset = func_ptr - base_addr;
log_message(log_file, true, "Offset for '%s': 0x%llx\n", setting.c_str(), offset);
// Log the result in the log file
fprintf(log_file, " \"%s\" => 0x%llx,\n", setting.c_str(), offset);
}
fprintf(log_file, "};\n\n");
// Log end time
t = time(NULL);
if (localtime_s(&tm_info, &t) != 0) {
log_message(log_file, false, "Error: Could not get local time.\n");
}
else {
log_message(log_file, true, "Memory scan ended at: %04d-%02d-%02d %02d:%02d:%02d\n",
tm_info.tm_year + 1900, tm_info.tm_mon + 1, tm_info.tm_mday,
tm_info.tm_hour, tm_info.tm_min, tm_info.tm_sec);
}
// Cleanup
CloseHandle(hProcess);
fclose(log_file);
return 0;
}
Certainly! Below is a completely new implementation of a Memory Pattern Scanner in C++. This tool allows you to search for specific byte patterns within the memory space of a running process. This can be useful for various legitimate purposes such as debugging, reverse engineering, or educational purposes.
Disclaimer:
Modifying or inspecting the memory of processes you do not own or have permission to interact with may violate software licenses or laws. Use this tool responsibly and ethically.
Overview
Memory Pattern Scanner performs the following tasks:
Process Identification:
Locates a running process by its name and retrieves its Process ID (PID).
Module Enumeration:
Enumerates all modules (DLLs and EXEs) loaded within the target process.
Pattern Scanning:
Searches for a specific byte pattern within the memory regions of each module.
Supports wildcard bytes (?) in the pattern to allow flexible searching.
Logging:
Outputs the results to both the console and a log file (pattern_scan.log).
Logs include timestamps, found pattern addresses, and module information.
Error Handling:
Comprehensive error checking to ensure robustness.
Key Features
Wildcard Support:
Allows searching for patterns with unknown bytes using ?. For example, 48 8B ?? ?? ?? 89 searches for 48 8B followed by any three bytes, then 89.
Modular Design:
Functions are modularized for clarity and maintainability.
Comprehensive Logging:
Detailed logs provide insights into the scanning process and results.
Implementation
Below is the complete C++ code for the Memory Pattern Scanner:
cpp
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <ctime>
// Function to log messages to console and optionally to a file
void LogMessage(std::ofstream& logFile, bool logToFile, const std::string& message) {
// Output to console
std::cout << message;
// Output to log file if enabled
if (logToFile && logFile.is_open()) {
logFile << message;
logFile.flush();
}
}
// Function to get the Process ID (PID) by process name
DWORD GetProcessID(const std::string& processName, std::ofstream& logFile) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
LogMessage(logFile, true, "Error: Unable to create tool help snapshot.\n");
return 0;
}
if (!Process32First(hSnapshot, &pe32)) {
LogMessage(logFile, true, "Error: Unable to retrieve information on the first process.\n");
CloseHandle(hSnapshot);
return 0;
}
DWORD pid = 0;
do {
std::wstring ws(pe32.szExeFile);
std::string exeFile(ws.begin(), ws.end());
if (_stricmp(exeFile.c_str(), processName.c_str()) == 0) {
pid = pe32.th32ProcessID;
LogMessage(logFile, true, "Process '" + processName + "' found with PID: " + std::to_string(pid) + "\n");
break;
}
} while (Process32Next(hSnapshot, &pe32));
if (pid == 0) {
LogMessage(logFile, true, "Error: Process '" + processName + "' not found.\n");
}
CloseHandle(hSnapshot);
return pid;
}
// Function to parse the pattern string into a byte array and mask
bool ParsePattern(const std::string& pattern, std::vector<BYTE>& bytes, std::string& mask) {
std::istringstream iss(pattern);
std::string byteString;
while (iss >> byteString) {
if (byteString == "?") {
bytes.push_back(0x00);
mask += "?";
}
else if (byteString.find("?") != std::string::npos) {
// Partial wildcard, replace unknown nibble with 0
BYTE byte = 0;
if (byteString[0] != '?') {
byte |= (BYTE)(strtoul(byteString.substr(0, 1).c_str(), nullptr, 16) << 4);
}
if (byteString[1] != '?') {
byte |= (BYTE)(strtoul(byteString.substr(1, 1).c_str(), nullptr, 16));
}
bytes.push_back(byte);
mask += "?";
}
else {
bytes.push_back((BYTE)strtoul(byteString.c_str(), nullptr, 16));
mask += "x";
}
}
return !bytes.empty();
}
// Function to get all modules of a process
bool GetProcessModules(DWORD pid, std::vector<HMODULE>& modules, std::ofstream& logFile) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
if (hSnapshot == INVALID_HANDLE_VALUE) {
LogMessage(logFile, true, "Error: Unable to create module snapshot.\n");
return false;
}
MODULEENTRY32 me32;
me32.dwSize = sizeof(MODULEENTRY32);
if (!Module32First(hSnapshot, &me32)) {
LogMessage(logFile, true, "Error: Unable to retrieve information on the first module.\n");
CloseHandle(hSnapshot);
return false;
}
do {
modules.push_back(me32.hModule);
} while (Module32Next(hSnapshot, &me32));
CloseHandle(hSnapshot);
return true;
}
// Function to convert byte to uppercase hex string
std::string ByteToHex(BYTE byte) {
std::stringstream ss;
ss << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << (int)byte;
return ss.str();
}
// Function to scan a memory buffer for a pattern
std::vector<uintptr_t> ScanBuffer(const BYTE* buffer, SIZE_T bufferSize, const std::vector<BYTE>& pattern, const std::string& mask) {
std::vector<uintptr_t> matches;
size_t patternSize = pattern.size();
size_t maskSize = mask.size();
if (patternSize != maskSize || bufferSize < patternSize) {
return matches;
}
for (SIZE_T i = 0; i <= bufferSize - patternSize; ++i) {
bool found = true;
for (size_t j = 0; j < patternSize; ++j) {
if (mask[j] == 'x' && buffer[i + j] != pattern[j]) {
found = false;
break;
}
}
if (found) {
matches.push_back(i);
}
}
return matches;
}
// Function to perform pattern scanning on all modules
void PerformPatternScan(HANDLE hProcess, const std::vector<HMODULE>& modules, const std::vector<BYTE>& pattern, const std::string& mask, std::ofstream& logFile) {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
SIZE_T pageSize = sysInfo.dwPageSize;
for (const auto& module : modules) {
MODULEINFO modInfo;
if (!GetModuleInformation(hProcess, module, &modInfo, sizeof(MODULEINFO))) {
LogMessage(logFile, true, "Warning: Unable to get information for a module.\n");
continue;
}
uintptr_t moduleBase = reinterpret_cast<uintptr_t>(modInfo.lpBaseOfDll);
SIZE_T moduleSize = modInfo.SizeOfImage;
LogMessage(logFile, true, "Scanning Module: " + std::string(PathFindFileNameA((LPCSTR)moduleBase)) + " | Base Address: 0x" +
std::to_string(moduleBase) + " | Size: " + std::to_string(moduleSize) + " bytes\n");
std::vector<char> buffer(moduleSize);
SIZE_T bytesRead;
if (!ReadProcessMemory(hProcess, (LPCVOID)moduleBase, buffer.data(), moduleSize, &bytesRead)) {
LogMessage(logFile, true, "Warning: Unable to read memory for module at 0x" + std::to_string(moduleBase) + "\n");
continue;
}
std::vector<uintptr_t> offsets = ScanBuffer(reinterpret_cast<BYTE*>(buffer.data()), bytesRead, pattern, mask);
for (const auto& offset : offsets) {
uintptr_t address = moduleBase + offset;
std::stringstream ss;
ss << std::hex << "Pattern found at address: 0x" << address << "\n";
LogMessage(logFile, true, ss.str());
}
if (offsets.empty()) {
LogMessage(logFile, true, "No matches found in this module.\n");
}
}
}
int main() {
std::string targetProcessName;
std::string patternInput;
std::cout << "Enter the target process name (e.g., notepad.exe): ";
std::cin >> targetProcessName;
std::cout << "Enter the byte pattern to search (e.g., 48 8B ?? ?? 89): ";
std::cin.ignore(); // Ignore leftover newline
std::getline(std::cin, patternInput);
// Parse the pattern
std::vector<BYTE> pattern;
std::string mask;
if (!ParsePattern(patternInput, pattern, mask)) {
std::cerr << "Error: Invalid pattern.\n";
return 1;
}
// Open log file
std::ofstream logFile("pattern_scan.log", std::ios::out);
if (!logFile.is_open()) {
std::cerr << "Error: Could not open log file for writing.\n";
return 1;
}
// Log start time
std::time_t t = std::time(nullptr);
char timeStr[100];
if (std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&t))) {
LogMessage(logFile, true, "Memory Pattern Scan Started at: " + std::string(timeStr) + "\n\n");
}
// Get Process ID
DWORD pid = GetProcessID(targetProcessName, logFile);
if (pid == 0) {
LogMessage(logFile, true, "Exiting program.\n");
logFile.close();
return 1;
}
// Open Process with necessary permissions
HANDLE hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess == NULL) {
LogMessage(logFile, true, "Error: Could not open process. Error Code: " + std::to_string(GetLastError()) + "\n");
logFile.close();
return 1;
}
// Get all modules of the process
std::vector<HMODULE> modules;
if (!GetProcessModules(pid, modules, logFile)) {
LogMessage(logFile, true, "Error: Could not retrieve modules.\n");
CloseHandle(hProcess);
logFile.close();
return 1;
}
// Perform Pattern Scanning
PerformPatternScan(hProcess, modules, pattern, mask, logFile);
// Log end time
t = std::time(nullptr);
if (std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&t))) {
LogMessage(logFile, true, "\nMemory Pattern Scan Ended at: " + std::string(timeStr) + "\n");
}
// Cleanup
CloseHandle(hProcess);
logFile.close();
std::cout << "Pattern scanning completed. Check 'pattern_scan.log' for details.\n";
return 0;
}
Explanation
1. Logging Mechanism
LogMessage Function:
Handles logging messages to both the console and a log file. This ensures that all actions and results are recorded for later review.
2. Process Identification
GetProcessID Function:
Takes a process name and scans all running processes to find a match. If found, it returns the corresponding PID.
3. Pattern Parsing
ParsePattern Function:
Converts a human-readable byte pattern string (e.g., 48 8B ?? ?? 89) into a byte array and a mask string. The mask uses x for fixed bytes and ? for wildcards.
4. Module Enumeration
GetProcessModules Function:
Retrieves all modules loaded within the target process. Modules include the main executable and any DLLs.
5. Pattern Scanning
ScanBuffer Function:
Scans a memory buffer for the specified byte pattern using the prepared mask. Returns the offsets where the pattern is found.
PerformPatternScan Function:
Iterates through each module, reads its memory, and uses ScanBuffer to find the pattern. Logs all found addresses.
6. Main Function Workflow
User Input:
Prompts the user to enter the target process name and the byte pattern to search for.
Pattern Parsing:
Converts the input byte pattern into a format suitable for scanning.
Process Access:
Retrieves the PID and opens a handle to the target process with the necessary permissions.
Module Retrieval:
Gathers all modules loaded in the process for scanning.
Scanning Execution:
Performs the pattern scanning across all modules and logs the findings.
Cleanup:
Closes the process handle and log file.
7. Error Handling
Comprehensive error messages guide the user in case of failures, such as inability to find the process, access memory, or parse the pattern correctly.
8. Wildcard Handling
Supports wildcard bytes (?) in the pattern, allowing users to search for patterns with unknown or variable bytes.
Usage Example
Compile the Code:
Use a C++ compiler like Visual Studio or g++ to compile the code.
Run the Executable:
Execute the compiled program. For example:
code
MemoryPatternScanner.exe
Provide Inputs:
Process Name:
Enter the name of the target process, e.g., notepad.exe.
Byte Pattern:
Enter the byte pattern to search for. Use spaces to separate bytes and ? for wildcards. For example:
code
48 8B ?? ?? 89
Review Results:
Console Output:
Displays real-time scanning progress and results.
Log File (pattern_scan.log):
Contains a detailed log of the scanning session, including timestamps and found addresses.
Notes
Permissions:
Ensure that you have the necessary permissions to access the target process. Running the scanner with elevated privileges (as Administrator) may be required for certain processes.
Architecture Compatibility:
The scanner is designed to handle both 32-bit and 64-bit processes, but attempting to scan a 64-bit process from a 32-bit scanner (or vice versa) may lead to issues.
Performance Considerations:
Scanning large modules or numerous patterns can be time-consuming. Optimize patterns and limit scanning to necessary modules when possible.
Safety Precautions:
Avoid scanning or interacting with critical system processes to prevent unintended behavior or system instability.
This new Memory Pattern Scanner tool provides a robust framework for searching byte patterns within a process's memory. Its modular design and comprehensive logging make it suitable for various applications in debugging and memory analysis.
Feel free to customize and enhance the tool further based on your specific requirements!