Advertisement
R3v3rs3r

Memory patch using OpenProcess function [C++]

Jul 24th, 2023
630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // patch.cpp
  2.  
  3. #include <iostream>
  4. #include <windows.h>
  5.  
  6. // The patched function with modified behavior
  7. int Patched_Add(int a, int b) {
  8.     // Let's return the product of the two numbers instead of the sum
  9.     return a * b;
  10. }
  11.  
  12. int main() {
  13.     // Target process information
  14.     const char* targetProcessName = "victim.exe";
  15.  
  16.     // Find the target process
  17.     HWND hWnd = FindWindowA(NULL, targetProcessName);
  18.     if (hWnd == NULL) {
  19.         std::cout << "Failed to find the target process." << std::endl;
  20.         return 1;
  21.     }
  22.  
  23.     // Get the process ID of the target process
  24.     DWORD pid;
  25.     GetWindowThreadProcessId(hWnd, &pid);
  26.  
  27.     // Open the target process with PROCESS_ALL_ACCESS permission
  28.     HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  29.     if (hProcess == NULL) {
  30.         std::cout << "Failed to open the target process." << std::endl;
  31.         return 1;
  32.     }
  33.  
  34.     // Get the address of the function to be patched
  35.     // In reality, this step can be more complex depending on the target function's location.
  36.     // For demonstration purposes, let's assume the address of the "Add" function is known.
  37.     DWORD addressToPatch = reinterpret_cast<DWORD>(Add);
  38.  
  39.     // Write the patched function into the target process
  40.     DWORD oldProtect;
  41.     VirtualProtectEx(hProcess, reinterpret_cast<LPVOID>(addressToPatch), sizeof(int), PAGE_EXECUTE_READWRITE, &oldProtect);
  42.     WriteProcessMemory(hProcess, reinterpret_cast<LPVOID>(addressToPatch), Patched_Add, sizeof(int), NULL);
  43.     VirtualProtectEx(hProcess, reinterpret_cast<LPVOID>(addressToPatch), sizeof(int), oldProtect, &oldProtect);
  44.  
  45.     // Close the process handle
  46.     CloseHandle(hProcess);
  47.  
  48.     std::cout << "Patching complete." << std::endl;
  49.  
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement