Here is some code this is supposed to inject my DLL and run it in notepad.exe but as the title states the CreateRemoteThread
call returns null
MyGetProcessId
works just fine I made it and checked its results to see if the pid was right and it was.
#define DLL_PATH "C:\\Users\\tkina\\Desktop\\3\\Dll1\\Debug\\Dll1.dll"
#include <Windows.h>
#include <iostream>
#include <tlhelp32.h>
DWORD MyGetProcessId(LPCTSTR ProcessName);
int main()
{
TCHAR Buffer[MAX_PATH];
DWORD err;
// Get full path of DLL to inject
DWORD pathLen = GetFullPathName(TEXT("mydll.dll"), MAX_PATH, Buffer, NULL);
PVOID addrLoadLibrary = (PVOID)GetProcAddress(GetModuleHandle(Buffer), "LoadLibraryA");
DWORD pID = MyGetProcessId(TEXT("Notepad.exe"));
// Open remote process
HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
if (!proc)
{
std::cout << "Could not open the process!\n";
system("pause");
}
// Get a pointer to memory location in remote process,
// big enough to store DLL path
PVOID memAddr = (PVOID)VirtualAllocEx(proc, 0, strlen(DLL_PATH)+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (NULL == memAddr) {
err = GetLastError();
return 0;
}
// Write DLL name to remote process memory
BOOL check = WriteProcessMemory(proc, memAddr, (LPVOID)DLL_PATH, strlen(DLL_PATH) + 1, NULL);
if (0 == check) {
err = GetLastError();
return 0;
}
// Open remote thread, while executing LoadLibrary
// with parameter DLL name, will trigger DLLMain
HANDLE hRemote = CreateRemoteThread(proc, 0, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"),
"LoadLibraryA"), (LPVOID)memAddr, 0,0);
if (NULL == hRemote) {
err = GetLastError();
return 0;
}
WaitForSingleObject(hRemote, INFINITE);
check = CloseHandle(hRemote);
VirtualFreeEx(proc, memAddr, strlen(DLL_PATH) + 1, MEM_RELEASE);
system("pause");
return 0;
}
The call to GetLastError
returned 5.