I was feeling a bit adventurous, so I thought about writing something like this under Windows, using the WinAPI, of course. Like Linux's ptrace
, the calls used by this code should only be used by debuggers and aren't normally seen in any normal application code.
Furthermore, opening another process' memory for writing requires you to open the process handle with PROCESS_VM_WRITE
and PROCESS_VM_OPERATION
privileges. This, however, is only possible if the application opening the process has the SeDebugPriviledge
priviledge enabled. I ran the application in elevated mode with administrator privileges, however I don't really know if that has any effect on the SeDebugPriviledge
.
Anyhow, here's the code that I used for this. It was compiled with VS2008.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char cmd[2048];
int a = 5;
printf("%p %d\n", &a, a);
sprintf(cmd, "MemChange.exe %lu %x", GetCurrentProcessId(), &a);
system(cmd);
printf("%p %d\n", &a, a);
return 0;
}
And here's the code for MemChange.exe
that this code calls.
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
DWORD pId;
LPVOID pAddr;
HANDLE pHandle;
SIZE_T bytesWritten;
int newValue = 666;
sscanf(argv[1], "%lu", &pId);
sscanf(argv[2], "%x", &pAddr);
pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pId);
WriteProcessMemory(pHandle, pAddr, &newValue, sizeof(newValue), &bytesWritten);
CloseHandle(pHandle);
fprintf(stderr, "Written %u bytes to process %u.\n", bytesWritten, pId);
return 0;
}
But please don't use this code. It is horrible, has no error checks and probably leaks like holy hell. It was created only to illustrate what can be done with WriteProcessMemory
. Hope it helps.