BOOL WINAPI InjectLibW(DWORD dwProcessId, PCWSTR pszLibFile)
{
//如果函数执行失败
BOOL bOk = FALSE;
HANDLE hProcess = NULL, hThread = NULL;
PWSTR pszLibFileRemote = NULL;
__try
{
hProcess = OpenProcess(
PROCESS_QUERY_INFORMATION |
PROCESS_CREATE_THREAD | //用于创建远程线程
PROCESS_VM_OPERATION | //用于virtualAllocEx/VirtualFreeEx
PROCESS_VM_WRITE, //用于写入进程内存
FALSE, dwProcessId);
if (hProcess == NULL)
__leave;
//计算DLL路径名所需的字节数
int cch = 1 + lstrlenW(pszLibFile);
int cb = cch * sizeof(wchar_t);
//在远程进程中为路径名分配空间
pszLibFileRemote = (PWSTR)
VirtualAllocEx(hProcess, NULL, cb, MEM_COMMIT, PAGE_READWRITE);
if (pszLibFileRemote == NULL)
__leave;
//复制DLL路径到远程进程地址空间
if (!WriteProcessMemory(hProcess, pszLibFileRemote, (PVOID)pszLibFile, cb, NULL))
__leave;
//获取在Kernel32中loadlibraryW的真实地址
PTHREAD_START_ROUTINE pfnThreadRtn = (PTHREAD_START_ROUTINE)
GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "LoadLibraryW");
if (pfnThreadRtn == NULL)
__leave;
//创建远程线程并调用LoadLibraryW(DLLPathname)
hThread = CreateRemoteThread(hProcess, NULL, 0,
pfnThreadRtn, pszLibFileRemote, 0, NULL);
if (hThread == NULL)
__leave;
WaitForSingleObject(hThread, INFINITE);
bOk = TRUE;
}
__finally
{
if (pszLibFileRemote != NULL)
VirtualFreeEx(hProcess, pszLibFileRemote, 0, MEM_RELEASE);
if (hThread != NULL)
CloseHandle(hThread);
if (hProcess != NULL)
CloseHandle(hProcess);
}
return bOk;
}