WriteProcessMemory() Error 998

2020-08-09 05:05发布

问题:

I'm getting error 998 (access denied) with writeprocessmemory in C++. I don't know what I'm doing wrong.

Here's some of my code:

DWORD ProcessId;
        GetWindowThreadProcessId(WindowHandle, &ProcessId); //pID
        if (ProcessId) {}
        else {
            cout << "ERROR! Process ID Could not be received." << endl;
            return 0;
        }

        //Get the Process Handle
        HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, false, ProcessId);
        if (ProcessId) {}
        else {
            cout << "ERROR! Process Handle could not be received." << endl;
            return 0;
        }

        //Get it done with.
        bool MemWritten = WriteProcessMemory(ProcessHandle, Address, &NewValue, sizeof(NewValue), NULL);

        //Close the process handle to prevent memory leak.
        CloseHandle(ProcessHandle);

回答1:

Before you can write to process memory you should reserve some memory pages with use of VirtualAllocEx.

Sample:

LPVOID lpRemoteAddress = VirtualAllocEx( hProcess, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
if( !lpRemoteAddress )
{
  return;
}
WriteProcessMemory( hProcess, lpRemoteAddress, .... /*your params here*/ )


回答2:

You do not have permission to modify executable memory. You must modify the permissions by running your program as administrator and wrapping your call to WriteProcessMemory() with a call to VirtualProtectEx().

void PatchEx(BYTE* dst, BYTE* src, unsigned int size, HANDLE hProcess)
{
    DWORD oldprotect;
    VirtualProtectEx(hProcess, dst, size, PAGE_EXECUTE_READWRITE, &oldprotect);
    WriteProcessMemory(hProcess, dst, src, size, nullptr);
    VirtualProtectEx(hProcess, dst, size, oldprotect, &oldprotect);
}

Using a function like this ensures you always change it to have write permissions.



标签: c++