3

I'm injecting a DLL into a process, in the entry point of that process I spawn a new thread and allocate a console, I redirect all std to the console, When I close the console window the whole process closes, Is there a way so that it won't close the process? This is my code:

entrypoint:

#pragma region EntryPoint
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
            {
                DWORD threadId;
                hProcess = GetCurrentProcess();
                hThread = CreateThread( NULL, 0, Attach, 0, 0, &threadId);
            } break;
        case DLL_PROCESS_DETACH:
            CloseHandle(hThread);
        break;
    }
    return TRUE;
}
#pragma endregion EntryPoint

Attach:

DWORD WINAPI Attach(LPVOID args)
{
    RedirectIOToConsole();
}

And this is the console code:

#include "hFatboy.h"

#ifndef _USE_OLD_IOSTREAMS
using namespace std;
#endif

static const WORD MAX_CONSOLE_LINES = 500;
extern HANDLE hProcess;

byte *readMemory(DWORD address, int length)
{
    byte *buffer = new byte[length];
    SIZE_T bytesRead;
    if (ReadProcessMemory(hProcess, (void *)address, buffer, length, &bytesRead))
        return buffer;

    return NULL;
}
void RedirectIOToConsole()
{
    int hConHandle;
    long lStdHandle;

    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    FILE *fp;

    AllocConsole();
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
    coninfo.dwSize.Y = MAX_CONSOLE_LINES;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);

    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

    fp = _fdopen( hConHandle, "w" );

    *stdout = *fp;

    setvbuf( stdout, NULL, _IONBF, 0 );

    lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

    fp = _fdopen( hConHandle, "r" );

    *stdin = *fp;

    setvbuf( stdin, NULL, _IONBF, 0 );

    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

    fp = _fdopen( hConHandle, "w" );

    *stderr = *fp;

    setvbuf( stderr, NULL, _IONBF, 0 );

    ios::sync_with_stdio();
}
Dean
  • 499
  • 6
  • 13
  • 34

1 Answers1

1

You can try to register a HandlerRoutine with SetConsoleCtrlHandler. You will then be able to intercept the closing event CTRL_CLOSE_EVENT and avoid the default behavior that is calling ExitProcess.

pagra
  • 665
  • 4
  • 11
  • @Dean, were you able to get the console control handler to work? I [cannot get my handler to work](http://stackoverflow.com/a/20234847/2392683) for **CTRL_CLOSE_EVENT**. My handler for **CTRL_C_EVENT** works just fine, however. – chwarr Nov 27 '13 at 06:57