使用 CreateRemoteThread 向宿主进程注入模块
思路:
1,获取宿主进程的进程句柄 hProc;
2,为宿主进程申请内存(VirtualAllocEx)
3,向申请的内存写入要加载的模块的名称(WriteProcessMemory)
4,获取当前进程的 LoadLibraryA 函数的地址(宿主进程的LoadLibrary函数的地址也是这个)
5,创建远程线程。
代码:
1 #include <Windows.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 char msg[128]; 6 7 BOOL myCreateRemoteThread(DWORD dwProcessId, char *LibName) { 8 /* 1, 获取进程句柄 */ 9 HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, NULL, dwProcessId); 10 if (!hProc) { 11 sprintf(msg, "OpenProcess faile: %d", GetLastError()); 12 MessageBox(NULL, msg, NULL, MB_OK); 13 return false; 14 } 15 16 /* 2, 为远程进程申请内存, 用于写入参数 */ 17 LPVOID p = VirtualAllocEx(hProc, NULL, 0x100, MEM_COMMIT, PAGE_READWRITE); 18 if (!p) { 19 sprintf(msg, "VirutalAllocEx failed: %d", GetLastError()); 20 MessageBox(NULL, msg, NULL, MB_OK); 21 CloseHandle(hProc); 22 return false; 23 } 24 25 int len = strlen(LibName) + 1; 26 27 /* 3, 将参数写入远程进程内存 */ 28 if (!WriteProcessMemory(hProc, p, LibName, len, NULL)) { 29 sprintf(msg, "WriteProcessMemory failed: %d", GetLastError()); 30 MessageBox(NULL, msg, NULL, MB_OK); 31 CloseHandle(hProc); 32 VirtualFreeEx(hProc, p, 0x100, MEM_RELEASE); 33 return false; 34 } 35 36 /* 4, 获取loadlibrary函数的地址 */ 37 HMODULE hModule = GetModuleHandle("Kernel32.dll"); 38 if (!hModule) { 39 sprintf(msg, "GetModuleHandle failed: %d", GetLastError()); 40 MessageBox(NULL, msg, NULL, MB_OK); 41 CloseHandle(hProc); 42 VirtualFreeEx(hProc, p, 0x100, MEM_RELEASE); 43 return false; 44 } 45 46 DWORD fun = (DWORD)GetProcAddress(hModule, "LoadLibraryA"); 47 if (!fun) { 48 sprintf(msg, "GetProcAddress failed: %d", GetLastError()); 49 MessageBox(NULL, msg, NULL, MB_OK); 50 CloseHandle(hProc); 51 VirtualFreeEx(hProc, p, 0x100, MEM_RELEASE); 52 return false; 53 } 54 55 HANDLE hThread = CreateRemoteThread(hProc, NULL, 0, LPTHREAD_START_ROUTINE(fun), p, 0, NULL); 56 if (!hThread) { 57 sprintf(msg, "CreateRemoteThread failed: %d", GetLastError()); 58 MessageBox(NULL, msg, NULL, MB_OK); 59 CloseHandle(hProc); 60 VirtualFreeEx(hProc, p, 0x100, MEM_RELEASE); 61 return false; 62 } 63 64 CloseHandle(hProc); 65 CloseHandle(hThread); 66 VirtualFreeEx(hProc, p, 0x100, MEM_RELEASE); 67 return true; 68 } 69 70 int main() { 71 72 DWORD pid; 73 scanf("%d", &pid); 74 75 myCreateRemoteThread(pid, "C:\\Documents and Settings\\0\\桌面\\DynamicLibrary.dll"); 76 77 return 0; 78 }
在Win10上调试,能注入,但是在宿主进程未检测到注入的 .dll 模块,在 xp 上 OpenProcess 返回 “拒绝访问"。等找到原因再回来附结果图。