Home > Back-end >  Why is my console not showing up when my Dll is loaded?
Why is my console not showing up when my Dll is loaded?

Time:07-08

I have two files, the file which I'll use to load the Dll into the process is the following:

#include <Windows.h>

int main()
{
    // path to our dll
    LPCSTR DllPath = any_path;

    // Open a handle to target process
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 26188);

    // Allocate memory for the dllpath in the target process
    // length of the path string   null terminator
    LPVOID pDllPath = VirtualAllocEx(hProcess, 0, strlen(DllPath)   1,
        MEM_COMMIT, PAGE_READWRITE);

    // Write the path to the address of the memory we just allocated
    // in the target process
    WriteProcessMemory(hProcess, pDllPath, (LPVOID)DllPath,
        strlen(DllPath)   1, 0);

    // Create a Remote Thread in the target process which
    // calls LoadLibraryA as our dllpath as an argument -> program loads our dll
    HANDLE hLoadThread = CreateRemoteThread(hProcess, 0, 0,
        (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"),
            "LoadLibraryA"), pDllPath, 0, 0);

    // Wait for the execution of our loader thread to finish
    WaitForSingleObject(hLoadThread, INFINITE);

    // Free the memory allocated for our dll path
    VirtualFreeEx(hProcess, pDllPath, strlen(DllPath)   1, MEM_RELEASE);

    return 0;
}

So far, it's working properly and loading the Dll into the file, however, the Dll doesn't seem to be working:

#include "pch.h"
#include <iostream>
#include <windows.h>
#include <TlHelp32.h>

DWORD WINAPI HackThread(HMODULE hModule)
{
    //Create Console
    AllocConsole();
    FILE* f;
    freopen_s(&f, "CONOUT$", "w", stdout);

    std::cout << "ttt" << std::endl;
    std::cin.get();
    fclose(f);
    FreeConsole();
    FreeLibraryAndExitThread(hModule, 0);
    return 0;
}

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)HackThread, hModule, 0, nullptr);
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

I know the Dll is loading properly because the process is hitting the 'DLL_PROCESS_ATTACH' case and when I tested it with a message box instead of the CreateThread, it showed up, however, I can't seem to make the console show up. What would be the problem?

CodePudding user response:

One issue I see is that your thread is re-mapping only stdout to the new console, but it is not re-mapping stdin as well. So it is quite likely (use a debugger to verify this) that std::cin.get() is failing and thus not blocking the thread from closing the console immediately after creating it.

  • Related