Pnig0s1992:算是復習了,最經典的教科書式的Dll注入。
總結一下基本的注入過程,分注入和卸載
注入Dll:
1,OpenProcess獲得要注入進程的句柄
2,VirtualAllocEx在遠程進程中開辟出一段內存,長度為strlen(dllname)+1;
3,WriteProcessMemory將Dll的名字寫入第二步開辟出的內存中。
4,CreateRemoteThread將LoadLibraryA作為線程函數,參數為Dll的名稱,創建新線程
5,CloseHandle關閉線程句柄
卸載Dll:
1,CreateRemoteThread將GetModuleHandle注入到遠程進程中,參數為被注入的Dll名
2,GetExitCodeThread將線程退出的退出碼作為Dll模塊的句柄值。
3,CloseHandle關閉線程句柄
3,CreateRemoteThread將FreeLibraryA注入到遠程進程中,參數為第二步獲得的句柄值。
4,WaitForSingleObject等待對象句柄返回
5,CloseHandle關閉線程及進程句柄。
//Code By Pnig0s1992 //Date:2012,3,13 #include <stdio.h> #include <Windows.h> #include <TlHelp32.h> DWORD getProcessHandle(LPCTSTR lpProcessName)//根據進程名查找進程PID { DWORD dwRet = 0; HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if(hSnapShot == INVALID_HANDLE_VALUE) { printf("\n獲得進程快照失敗%d",GetLastError()); return dwRet; } PROCESSENTRY32 pe32;//聲明進程入口對象 pe32.dwSize = sizeof(PROCESSENTRY32);//填充進程入口對象大小 Process32First(hSnapShot,&pe32);//遍歷進程列表 do { if(!lstrcmp(pe32.szExeFile,lpProcessName))//查找指定進程名的PID { dwRet = pe32.th32ProcessID; break; } } while (Process32Next(hSnapShot,&pe32)); CloseHandle(hSnapShot); return dwRet;//返回 } INT main(INT argc,CHAR * argv[]) { DWORD dwPid = getProcessHandle((LPCTSTR)argv[1]); LPCSTR lpDllName = "EvilDll.dll"; HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_WRITE,FALSE,dwPid); if(hProcess == NULL) { printf("\n獲取進程句柄錯誤%d",GetLastError()); return -1; } DWORD dwSize = strlen(lpDllName)+1; DWORD dwHasWrite; LPVOID lpRemoteBuf = VirtualAllocEx(hProcess,NULL,dwSize,MEM_COMMIT,PAGE_READWRITE); if(WriteProcessMemory(hProcess,lpRemoteBuf,lpDllName,dwSize,&dwHasWrite)) { if(dwHasWrite != dwSize) { VirtualFreeEx(hProcess,lpRemoteBuf,dwSize,MEM_COMMIT); CloseHandle(hProcess); return -1; } }else { printf("\n寫入遠程進程內存空間出錯%d。",GetLastError()); CloseHandle(hProcess); return -1; } DWORD dwNewThreadId; LPVOID lpLoadDll = LoadLibraryA; HANDLE hNewRemoteThread = CreateRemoteThread(hProcess,NULL,0,(LPTHREAD_START_ROUTINE)lpLoadDll,lpRemoteBuf,0,&dwNewThreadId); if(hNewRemoteThread == NULL) { printf("\n建立遠程線程失敗%d",GetLastError()); CloseHandle(hProcess); return -1; } WaitForSingleObject(hNewRemoteThread,INFINITE); CloseHandle(hNewRemoteThread); //准備卸載之前注入的Dll DWORD dwHandle,dwID; LPVOID pFunc = GetModuleHandleA;//獲得在遠程線程中被注入的Dll的句柄 HANDLE hThread = CreateRemoteThread(hProcess,NULL,0,(LPTHREAD_START_ROUTINE)pFunc,lpRemoteBuf,0,&dwID); WaitForSingleObject(hThread,INFINITE); GetExitCodeThread(hThread,&dwHandle);//線程的結束碼即為Dll模塊兒的句柄 CloseHandle(hThread); pFunc = FreeLibrary; hThread = CreateRemoteThread(hThread,NULL,0,(LPTHREAD_START_ROUTINE)pFunc,(LPVOID)dwHandle,0,&dwID); //將FreeLibraryA注入到遠程線程中去卸載Dll WaitForSingleObject(hThread,INFINITE); CloseHandle(hThread); CloseHandle(hProcess); return 0; }
本文出自 “About:Blank H4cking” 博客,請務必保留此出處http://pnig0s1992.blog.51cto.com/393390/804484