Reputation: 31
I have a code which injects a dll to a process. The process which executes the injection function is always in the same architecture (x86 or x64) as the injected process. But for some reason, the CreateRemoteThread function call fails on Win7 64 bit OS, when the injecting and injected processes are of x86 architecture. Surprisingly, when the OS is Win10 64bit. 32 bit processes work fine. The code also works well for Win7 64 bit with 64 bit processes, and for Win7 32 bit with 32 bit processes.
I've looked over the internet for a possible cause and all I could find is that in Win7 there are sometimes issues with process sessions. I don't think this is the case since both the injecting and injected processes are "user" sessions.
When running GetLastError() I get 5 (ERROR_ACCESS_DENIED)
This is my injection function:
DWORD Inject(DWORD PID, const char *dllname)
{
HANDLE hThread = NULL;
BOOL writeSucceed = false;
int cch = 0;
cout << "Injector.dll : Injecting " << dllname << " to " << PID << endl;
DWORD hLibModule;
HMODULE hKernel32 = GetModuleHandle (TEXT ("Kernel32"));
void *hProcess = OpenProcess (PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION |
PROCESS_VM_WRITE, false, PID);
cch = strlen (dllname) + 1;
void *pLibRemote = VirtualAllocEx (hProcess, NULL, cch, MEM_COMMIT,
PAGE_READWRITE);
writeSucceed = WriteProcessMemory (hProcess, pLibRemote, (void *) dllname, cch, NULL);
hThread = CreateRemoteThread (hProcess, NULL, 0,
(PTHREAD_START_ROUTINE)
GetProcAddress (hKernel32,
"LoadLibraryA"),
pLibRemote, 0, NULL);
WaitForSingleObject (hThread, INFINITE);
GetExitCodeThread( hThread, &hLibModule );
CloseHandle (hThread);
VirtualFreeEx (hProcess, pLibRemote, sizeof (dllname), MEM_RELEASE);
hThread = CreateRemoteThread (hProcess, NULL, 0,
(PTHREAD_START_ROUTINE) GetProcAddress (hKernel32,
"FreeLibrary"),
(void *) hLibModule, 0, NULL);
WaitForSingleObject (hThread, INFINITE);
CloseHandle (hThread);
return 0;
}
Is there some special treatment I should do in code for Windows 7?
Upvotes: 0
Views: 831
Reputation: 31
The problem was that I had to add PROCESS_QUERY_INFORMATION
to the OpenProcess
flags. This was very tricky, since if you don't include this flag, it will still work everywhere except the case of Win7 64bit OS and 32bit application.
Upvotes: 3