参考了 Window 核心编程里的远程注入 DLL。远程注入 DLL 成功后,某些程序没有运行 DLL,有些程序正常执行了 DLL,这是什么原因?
DLL 里只是简单的调用了下 messagebox
代码如下:
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;
}