#include <Windows.h>
#include <tchar.h>
BOOL RemoteInjectDll(DWORD PID, LPCTSTR dllpath)
{
BOOL status = FALSE;
HANDLE hProcess = NULL, hThread = NULL;
HMODULE hMod = NULL;
PWSTR remote_buffer = NULL;
int len_dllpath = 1 + lstrlen(dllpath);
int dllpath_memory = len_dllpath * sizeof(wchar_t);
PTHREAD_START_ROUTINE get_func_address = NULL;
__try
{
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
_tprintf(L"Injecting DLL to PID: %lu \n", PID);
if (hProcess == NULL)
{
_tprintf(L"Get Process Handle Error : %lu \n", GetLastError());
__leave;
}
__try
{
remote_buffer = (PWSTR)VirtualAllocEx(hProcess, NULL, dllpath_memory, MEM_COMMIT, PAGE_READWRITE);
if (remote_buffer == NULL)
{
_tprintf(L"VirtualAlloc Error %lu \n", GetLastError());
__leave;
}
}
__finally
{
_tprintf(L"VirtualAlloc Done\n");
}
if (!WriteProcessMemory(hProcess, remote_buffer, (PVOID)dllpath, dllpath_memory, NULL)) __leave;
hMod = GetModuleHandle(L"kernel32.dll");
get_func_address = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "LoadLibraryW");
if (get_func_address == NULL)
{
_tprintf(L"Get LoadLibrary Address Error %lu \n", GetLastError());
__leave;
}
hThread = CreateRemoteThread(hProcess, NULL, 0, get_func_address, remote_buffer, 0, NULL);
if (hThread == NULL)
{
_tprintf(L"CreateRemoteThread Error %lu \n", GetLastError());
__leave;
}
WaitForSingleObject(hThread, INFINITE);
status = TRUE;
}
__finally
{
if (remote_buffer != NULL)
VirtualFreeEx(hProcess, remote_buffer, 0, MEM_RELEASE);
if (hThread != NULL)
CloseHandle(hThread);
if (hProcess != NULL)
CloseHandle(hProcess);
}
return(status);
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
if (argc != 3)
{
_tprintf(L"Usage: %s <pid> <dll path> \n", argv[0]);
return(1);
}
if (RemoteInjectDll((DWORD)_tstol(argv[1]), argv[2]))
{
_tprintf(L"InjectDll Sucess \n");
}
else
{
_tprintf(L"InjectDll Fail \n");
}
return(0);
}