本文记录学习远程线程注入dll的过程
思路:通过LoadLibrary函数将自己的dll加载至目标进程的空间并执行代码。
具体实现步骤:
- 在A进程中分配空间,存储"X.dll"的文件路径
- 获取LoadLibrary函数的地址
- 创建远程线程,执行LoadLibrary函数
涉及的具体api函数:
- LoadLibraryA
- VirtualAllocEx
- WriteProcessMemory
具体代码实现:
dll:
1 DWORD WINAPI ThreadProc(LPVOID lpParameter){ 2 for (int i = 0; i < 10; i ++) 3 { 4 Sleep(1000); 5 printf("From 6.dll: Mz1真帅! "); 6 } 7 return 0; 8 } 9 BOOL APIENTRY DllMain( HANDLE hModule, 10 DWORD ul_reason_for_call, 11 LPVOID lpReserved 12 ) 13 { 14 15 switch ( ul_reason_for_call) 16 { 17 case DLL_PROCESS_ATTACH: 18 CreateThread(NULL,0, 19 (LPTHREAD_START_ROUTINE)ThreadProc, 20 NULL, 0,NULL);//创建新线程执行代码 21 break; 22 case DLL_PROCESS_DETACH: 23 break; 24 case DLL_THREAD_ATTACH: 25 break; 26 case DLL_THREAD_DETACH: 27 break; 28 } 29 30 return TRUE; 31 }
执行注入的程序代码:
1 //远程线程注入 2 BOOL load_dll(DWORD dwProcessID, char* szDllPathName) 3 //进程PID和dll完整的路径 4 { 5 BOOL bRet; 6 HANDLE hProcess; 7 HANDLE hThread; 8 DWORD dwLength; 9 DWORD dwLoadAddr; 10 LPVOID lpAllocAddr; 11 DWORD dwThreadID; 12 HMODULE hModule; 13 //获取进程句柄 14 hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwProcessID); 15 printf("%x ", hProcess); 16 if (hProcess == NULL) 17 { 18 OutputDebugString("fail to open process "); 19 return FALSE; 20 } 21 //把DLL文件路径字符串存入被注入进程的内存空间 22 //计算dll路径名字长度,并且加上结尾0的空间 23 dwLength = strlen(szDllPathName)+1; 24 //远程申请内存空间 25 lpAllocAddr = (LPVOID)VirtualAllocEx(hProcess,NULL,dwLength,MEM_COMMIT,PAGE_READWRITE); 26 if (lpAllocAddr == NULL){ 27 OutputDebugString("VirtualAllocEx error "); 28 CloseHandle(hProcess); 29 return FALSE; 30 } 31 //拷贝dll路径名字到目标进程的内存 32 bRet = WriteProcessMemory(hProcess, lpAllocAddr,szDllPathName,dwLength,NULL); 33 if (bRet == NULL){ 34 OutputDebugString("bRet error "); 35 CloseHandle(hProcess); 36 return FALSE; 37 } 38 //获取kernel32.dll的地址 39 hModule = GetModuleHandle("Kernel32.dll"); 40 if (!hModule) 41 { 42 OutputDebugString("GetModuleHandle error "); 43 CloseHandle(hProcess); 44 return FALSE; 45 } 46 //获取LoadLibraryA函数地址 47 dwLoadAddr = (DWORD)GetProcAddress(hModule, "LoadLibraryA"); 48 if (!dwLoadAddr ) 49 { 50 OutputDebugString("GetProcAddress error "); 51 CloseHandle(hProcess); 52 CloseHandle(hModule); 53 return FALSE; 54 } 55 56 //创建远程线程,加载dll 57 hThread = CreateRemoteThread(hProcess, NULL, 0, (unsigned long (__stdcall *)(void *))dwLoadAddr, lpAllocAddr, 0, NULL); 58 printf("%x ", hThread); 59 if (hThread == NULL) 60 { 61 OutputDebugString("fail to open RomoteThread "); 62 CloseHandle(hProcess); 63 return FALSE; 64 } 65 CloseHandle(hProcess); 66 67 return TRUE; 68 } 69 70 //之后在main函数中调用即可 71 //例:load_dll(1304, "C:\Documents and Settings\Administrator\桌面\线程注入\6.dll");
简单效果图: