I'm trying to call a process from another program, this process being one I've injected via DLL. The first one, where we load the library "Client.dll" works perfectly, this is sown by the MessageBox Debug in DllMain (DLL_PROCESS_ATTACH).
Once the DLL is loaded into the program, I try to call the function MainThread from Client.dll this however using the same method (copied, pasted, edited) doesn't work. Both are posted below, can anyone tell me why? I have removed all code from MainThread but that for debug reasons.
Here is Main Thread:
void MainThread(void * Arguments)
{
MessageBoxA(NULL, "MainThread Started!", "bla", MB_OK); //Not Shown
for (;;)
{
//This loop is here for the main program loop.
}
_endthread();
}
Here is how I load Client.dll and try to call Main Thread, keep in mind the actual injection works but not the starting of Main Thread.
bool InjectDLL(DWORD ProcessID, const char* Path)
{
HANDLE Handle = OpenProcess(PROCESS_ALL_ACCESS, false, ProcessID);
if (!Handle)
{
std::cout << "Could not access process! Inject Failed!";
return false;
}
LPVOID LoadLibraryAddress = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
LPVOID Allocate = VirtualAllocEx(Handle, NULL, strlen(Path), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(Handle, Allocate, Path, strlen(Path), NULL);
HANDLE Thread = CreateRemoteThread(Handle, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddress, Allocate, 0, NULL);
WaitForSingleObject(Thread, INFINITE); // WAIT FOREVER!
VirtualFreeEx(Handle, Thread, strlen(Path), MEM_RELEASE);
//Start DLL Main Thread
LPVOID MainThreadAddress = (LPVOID)GetProcAddress(GetModuleHandleA("Client.dll"), "MainThread");
Allocate = VirtualAllocEx(Handle, NULL, 0, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(Handle, Allocate, Path, strlen(Path), NULL);
HANDLE MainThread = CreateRemoteThread(Handle, NULL, NULL, (LPTHREAD_START_ROUTINE)MainThreadAddress, Allocate, 0, NULL);
WaitForSingleObject(MainThread, INFINITE); // Wait for Main Thread to start
VirtualFreeEx(Handle, MainThread, strlen(Path), MEM_RELEASE);
CloseHandle(MainThread);
CloseHandle(Thread);
CloseHandle(Handle);
return true;
}
Thanks to anyone who can help.
I don't see any error checking - specifically for the case where you're fetching the address of "MainThread". Is this succeeding?
In order for this to work, you're going to need to explicitly export "MainThread" from your DLL either via a .DEF file or by using __declspec( dllexport )
. See this SO link for details.