[C] Dll Injection Using SetWindowsHookEx()

Arhiva forumului

Moderatori: Moderator Global, Administrator

Fabr3gas

CODE INFO
The SetWindowsHookEx method

The 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

Cod: Selectaţi tot

#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; 
}
Încuiat

Înapoi la “Arhiva forum”