MyUsername112358
MyUsername112358

Reputation: 1307

Injecting a x86 target with a x86 dll from a x64 injector

I'm having a bit of trouble doing exactly what the title says... I made an injector that works with x86 to x86 and x64 to x64, but injecting x86 from a x64 (with a x86 dll) doesn't work with that code:

#include <Windows.h>
#include <string>

bool InjectDll(DWORD processId, std::string dllPath)
{
    HANDLE hThread, hProcess;
    void*  pLibRemote = 0;  // the address (in the remote process) where
                            // szLibPath will be copied to;

    HMODULE hKernel32 = GetModuleHandle("Kernel32");

    char DllFullPathName[_MAX_PATH];
    GetFullPathName(dllPath.c_str(), _MAX_PATH, DllFullPathName, NULL);

    // Get process handle
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);

    // copy file path in szLibPath
    char szLibPath[_MAX_PATH];
    strcpy_s(szLibPath, DllFullPathName);

    // 1. Allocate memory in the remote process for szLibPath
    pLibRemote = VirtualAllocEx(hProcess, NULL, sizeof(szLibPath),
                                MEM_COMMIT, PAGE_READWRITE);

    if (pLibRemote == NULL)
        return false;

    // 2. Write szLibPath to the allocated memory
    WriteProcessMemory(hProcess, pLibRemote, (void*)szLibPath,
                       sizeof(szLibPath), NULL);

    // 3. Force remote process to load dll
    LPTHREAD_START_ROUTINE thread;
    thread = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32,"LoadLibraryA");

    hThread = CreateRemoteThread(hProcess, NULL, 0, thread,  pLibRemote,
                                 0, NULL);

    if (hThread == NULL)
        return false;

    return true;
}

The function returns true in every scenario (even from a 64 bit injector injecting a 32bit process), yet it fails to actually inject the dll.

By the way, during my research I found those questions:

x86 Code Injection into an x86 Process from a x64 Process

C++: Injecting 32 bit targets from 64 bit process

But while the answers explain how, I didn't manage to actually do it... so maybe all I need is a code snippet to send me on the right way?

Upvotes: 1

Views: 2924

Answers (1)

MyUsername112358
MyUsername112358

Reputation: 1307

Changing this line:

thread = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32,"LoadLibraryA");

for this line:

thread = (LPTHREAD_START_ROUTINE)system("loadLibrary_x86_address.exe");

with "loadLibrary_x86_address.exe" being a 32 bit app defined as:

#include <Windows.h>

int main()
{
    return (int)LoadLibraryA;
}

Works! It's kind of a hack, but it does the job.

Upvotes: 3

Related Questions