Search code examples
c++winapidlldll-injection

How to inject a dll to a another process?


I have been trying for the last few days to create a DLL injector.
The simplest method I found for DLL injection is using CreateRemoteThread

This is what I have written so far, this code doesn't work and cannot find out why.

I am pretty sure that my problem is in the variables types I am using to call the WinAPI functions but I cannot find where.

bool Injector::Inject( HANDLE hProcess )
{
    //hProcess is a process with writing and reading access
    HANDLE hThread;
    void*  pLibRemote = 0;  
    string dllPath = "Some dll path";
    HMODULE hKernel32 = GetModuleHandle(__TEXT("Kernel32"));


    pLibRemote = VirtualAllocEx(hProcess, NULL, sizeof(dllPath.c_str()), MEM_COMMIT, PAGE_READWRITE);

    WriteProcessMemory(hProcess, pLibRemote, dllPath.c_str(), sizeof(dllPath.c_str()), NULL);

    hThread = CreateRemoteThread( hProcess, NULL, 0,    
                    (LPTHREAD_START_ROUTINE) ::GetProcAddress(hKernel32,"LoadLibraryA"), 
                    pLibRemote, 0, NULL );


    .
    .
    .

    CloseHandle(hThread);

    }
.
.
.

Solution

  • At least 2 problems :

    pLibRemote = VirtualAllocEx(hProcess, NULL, sizeof(dllPath.c_str()), MEM_COMMIT, PAGE_READWRITE);
    

    1) sizeof(dllPath.c_str()) : you are doing sizeof on a pointer (c_str() returns a pointer), hence you'll probably get 4 or 8 as a result. Use dllPath.size() + sizeof(char) (or wchar_t instead of char if using std::wstring).

    2) Use MEM_RESERVE | MEM_COMMIT instead of just MEM_COMMIT : you want to reserve and commit the reserved memory at the same time.

    Also ensure both programs use the same ISA (x86 / x86 ; x64 / x64, but not a mismatched ISA).