Search code examples
c++moduleloadlibrarydll-injection

Injected DLL not correct HMODULE


So I am injecting a DLL into a program. I can verify that the DLL is injected with help from Process Explorer. After the injection I am looping all modules from the process, comparing the names and return the injected dll as a HMODULE.

Then I GetProcAddress() this HMODULE to find a extern function inside of it, but for some reason this does not work properly.

HMODULE dllAddress = getModuleAddressFromProc(pid, "NewDll.dll");
externCreateThread createThread = (externCreateThread)GetProcAddress(dllAddress, "createThread");

When I breakpoint and check dllAddress it says:

enter image description here

When I use LoadLibrary to load the DLL in my current program and use that as a HMODULE, it does work.

HMODULE dllAddress = LoadLibrary(L"C:\\NewDll.dll");
externCreateThread createThread = (externCreateThread)GetProcAddress(dllAddress, "createThread");

Breakpointing to check dllAddress:

enter image description here

The returned HMODULE from the list of HMODULES is not the same as the HMODULE from LoadLibrary. Although the pointer address is the same.

Listing all the modules from the process is done with the code Microsoft provides. I altered it a bit to work with string comparison, but that does not effect the HMODULE type.

HMODULE getModuleAddressFromProc(DWORD pid, string moduleName) {
    HMODULE hMods[1024];
    DWORD cbNeeded;
    HMODULE output;
    unsigned int i;
    HANDLE newHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
    if (EnumProcessModules(newHandle, hMods, sizeof(hMods), &cbNeeded)) {
        for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
            TCHAR szModName[MAX_PATH];
            if (GetModuleFileNameEx(newHandle, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) {
                string s2 = charToString(szModName);
                if (s2.find(moduleName) != string::npos) {
                    output = hMods[i];
                    break;
                }
            }
        }
    }
    return output;
}

Solution

  • Got it working with help from:

    RectangleEquals -> Answer