Stub Injection Fails when Process is executed
Im trying to inject a DLL by writing a stub to allocated memory in the target process and changing the EIP register in the thread. It works fine when it is written after the process has already executed, but if I try and do it when the process first starts up it crashes the process.
Code:
void injectproxy(char szDll[MAX_PATH])
{
szDll = szGetDirFile(szDll);
stubLen = sizeof(stub);
DWORD dwProcId = NULL, threadID = NULL, oEIP = NULL, oldprot = NULL, dwLoadLibrary = NULL;
out("waiting for process");
CONTEXT ctx;
do
{
GetWindowTextA(g_hwEdit2, buf, sizeof(buf));
dwProcId = dwProcessID(buf);
}
while(dwProcId == NULL);
do
{
dwLoadLibrary = (DWORD)GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
}
while(dwLoadLibrary == NULL);
hProcess = OpenProcess((PROCESS_VM_WRITE | PROCESS_VM_OPERATION), false, dwProcId);
if(hProcess == NULL)
{
out("unable to open process!");
}
dllLen = strlen(szDll)+1;
addrDllPath = VirtualAllocEx(hProcess, NULL, dllLen, MEM_COMMIT, PAGE_READWRITE);
addrStub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if(addrStub == NULL)
{
sprintf(buf, "error code: %d", GetLastError());
out(buf);
return;
}
if(WriteProcessMemory(hProcess, addrDllPath, szDll, strlen(szDll), NULL) == 0)
{
out("WPM fail");
return;
}
do
threadID = GetMainThreadId(dwProcId);
while(threadID == 0);
hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME | SYNCHRONIZE ), false, threadID);
if(hThread == NULL)
{
sprintf(buf, "unable to open thread. error code:%d", GetLastError());
out(buf);
return;
}
SuspendThread(hThread);
ct*****ntextFlags = CONTEXT_CONTROL;
if(GetThreadContext(hThread, &ctx) == 0)
{
sprintf(buf,"failed to get thread context. error code:%d", GetLastError());
out(buf);
return;
}
oEIP = ctx.Eip;
ctx.Eip = (DWORD)addrStub;
ct*****ntextFlags = CONTEXT_CONTROL;
VirtualProtect(stub, stubLen, PAGE_EXECUTE_READWRITE, &oldprot);
memcpy((void *)((unsigned long)stub + 0x1), (void*)&oEIP, 4);
memcpy((void *)((unsigned long)stub + 0x8), (void*)&addrDllPath, 4);
memcpy((void *)((unsigned long)stub + 0xD), (void*)&dwLoadLibrary, 4);
if(WriteProcessMemory(hProcess, addrStub, (LPCVOID)stub, stubLen, NULL) == 0)
{
out("WPM fail");
return;
}
if(SetThreadContext(hThread, &ctx) == NULL)
{
out("unable to setthreadcontext");
}
if(ResumeThread(hThread) == 0xFFFFFFFF)
{
out("unable to resume the thread!");
}
}