C++ Dll injection — Hello world dll only works when injected into the same .exe that injects it

ccode-injectiondll

I've been working the past week on getting my simple injecting application to successfully inject dlls into other processes. So far however, it has only been working when I inject the dll into the injector itself. When I try to inject into a different application, my function reports success (the thread is successfully created, memory allocated and written into the target) but my dllMain appears to not be called. Additionally, the error code 0 (ERROR_SUCCESS) is specified by GetLastError().

When specifying the targetProcessId as GetCurrentProcess(), the dialog box shows and the RemoteThread is succesfully executed.

However, when I try to set the targetProcessId to a running instance of calc.exe, nothing happens. I've read elsewhere that calling MessageBox from a DllMain is a bad idea since its module might not have been loaded yet, so I also tried creating an infinite loop in my DllMain and checking if the thread count in calc.exe increased by 1. It remained unchanged.

This is my first question on StackOverflow and I tried to do as much research into this topic as possible before posting, but after many hours I have had no luck. I am obviously new to dll injection (I recently finished reading Ritcher's book, Windows via C/C++). Any help is greatly appreciated.

All of my code is being compiled from Visual Studio 2010 for the x64 platform.

Here's the relevant code below from my Injector application:

BOOL WINAPI Inject(DWORD processID, PCWSTR sourceDLL)
{
    BOOL success = false;
    HANDLE targetProcess = NULL, createdThread = NULL;
    PWSTR pszLibFileRemote = NULL;
    __try
    {
        std::cout << "Process ID: "<< processID << std::endl;
        targetProcess = OpenProcess(
            PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION  | PROCESS_VM_WRITE,
            FALSE, processID);
        if (targetProcess == NULL)
        {
            std::cout << "ERROR: " << GetLastError();
            MessageBox(NULL, L"Unable to open process.", L"Error", MB_OK);
            __leave;
        }

        int cch = 1 + lstrlenW(sourceDLL); //Calculate the number of bytes required for the DLL's path
        int cb = cch * sizeof(wchar_t);

        pszLibFileRemote = (PWSTR)VirtualAllocEx(targetProcess, NULL, cb, MEM_COMMIT, PAGE_READWRITE);
        if (pszLibFileRemote == NULL)
        {
            MessageBox(NULL, L"Could not allocate dll pathname in target process.", L"Error", MB_OK);
            __leave;
        }

        if (!WriteProcessMemory(targetProcess, pszLibFileRemote, (PVOID) sourceDLL, cb, NULL))
        {
            MessageBox(NULL, L"Could not write dll pathname in target process.", L"Error", MB_OK);
            __leave;
        }

        PTHREAD_START_ROUTINE pfnThreadRtn = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle(_T("Kernel32")), "LoadLibraryW");

        if (pfnThreadRtn == NULL)
        {
            MessageBox(NULL, L"Error finding LoadLibraryW address.", L"Error", MB_OK);
            __leave;
        }

        createdThread = CreateRemoteThread(targetProcess, NULL, 0, pfnThreadRtn, pszLibFileRemote, 0, NULL);
        if (createdThread == NULL)
        {
            __leave;
        }

        WaitForSingleObject(createdThread, INFINITE);
        success = true;

    }
    __finally { // Now, we can clean everything up
        // Free the remote memory that contained the DLL's pathname
        if (pszLibFileRemote != NULL)
            VirtualFreeEx(targetProcess, pszLibFileRemote, 0, MEM_RELEASE);
        if (createdThread != NULL)
            CloseHandle(createdThread);
        if (targetProcess != NULL)
            CloseHandle(targetProcess);
    }

    return success;
}
int _tmain(int argc, _TCHAR* argv[])
{
    PCWSTR srcDll = L"test.dll"; //dll in the same directory as the injector.exe, its code is specified below.
    DWORD processID = "768"; //Hard coded process ID of a running calc.exe. When I change this line to GetCurrentProcessId() the messagebox from my dll shows.      
    if (Inject(processID, srcDll))
    {
        std::cout << "Injection successful" << std::endl;
        Eject(processID, srcDll); //This detaches the dll by calling freelibrary from a remote thread. This function was omitted from this response to keep things relavent.
    }
    system("PAUSE");
    return 0;
}

And here is the code for my simple helloworld test.dll:

#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        MessageBox(NULL, L"HULLO.", L"DLL", MB_OK);
        break;
    case DLL_THREAD_ATTACH:
        MessageBox(NULL, L"HULLO.", L"DLL", MB_OK);
        break;
    case DLL_THREAD_DETACH:
        MessageBox(NULL, L"HULLO.", L"DLL", MB_OK);
        break;
    case DLL_PROCESS_DETACH:
        MessageBox(NULL, L"HULLO.", L"DLL", MB_OK);
        break;
    }
    return TRUE;
}

SOLVED: The injected dll's directory must be specified either relative to the target process or as a full path so the target process can find it. (I had it in my Injector's directory, which was causing the load problem — calc didnt know where it was.)

Best Answer

PCWSTR srcDll = L"test.dll"; //dll in the same directory as the injector.exe

Since you're executing LoadLibraryW() in the target program, not the injector, it doesn't know what "same directory as the injector" is - it just searches for it in standard directories documented on MSDN.

You need to pass the full path instead of the relative one.

Related Topic