How to call a specific function in a DLL injection?

The following code will enter dll and is called by DllMain. How do I call a specific function from a DLL, not just DllMain?

    DWORD pid;
    HANDLE hd;
    LPVOID gp, rs, proc;

    gp = (LPVOID)GetProcAddress(GetModuleHandle(L"Kernel32.dll"), "LoadLibraryA");
    pid = 6096;

    hd = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);    


    rs = (LPVOID)VirtualAllocEx(hd, 0, sizeof(DLL_NAME), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

    if (!WriteProcessMemory(hd, (LPVOID)rs, DLL_NAME, strlen(DLL_NAME), 0))
    {
        printf("WriteProcessMemory %d", GetLastError());
    }

    if (!CreateRemoteThread(hd, 0, 0, (LPTHREAD_START_ROUTINE)gp, rs, 0, 0))
    {
        printf("CreateRemoteThread %d", GetLastError());
    }
+4
source share
2 answers

When your embedded DLL DllMainstarts for the first time, call CreateThreadto create a new thread that can do whatever you like. Please note that you cannot call arbitrary code from DllMainas described in the documentation. Therefore, a call CreateThreadfrom DllMain.

+5
source

Well, I use the following approach.

DLL, , , :

#pragma data_seg(".MyShared")

LPTHREAD_START_ROUTINE g_lpMyFunc = NULL;

#pragma data_seg()
#pragma section(".MyShared", read, write, shared)

g_lpMyFunc DllMain :

BOOL APIENTRY DllMain(HMODULE, DWORD dwReasonForCall, LPVOID)
{
    if (NULL != GetModuleHandle(_T("MyApp.exe")))
    {
        if (DLL_PROCESS_ATTACH == dwReasonForCall)
        {
            g_lpMyFunc = (LPTHREAD_START_ROUTINE)&MyFunc;
        }
        else if (DLL_PROCESS_DETACH == dwReasonForCall)
        {
            g_lpMyFunc = NULL;
        }
    }
    return TRUE;
}

. GetModuleHandle MyApp. , , NULL, , DLL DllMain . , MyFunc g_lpMyFunc. DLL ( , ), g_lpMyFunc NULL, , .

MyFuncExtern, MyFunc :

extern "C" __declspec(dllexport) bool __cdecl MyFuncExtern(HANDLE hProcess)
{
    if (NULL == g_lpMyFunc)
    {
        return false;
    }

    return NULL != CreateRemoteThread(hProcess, NULL, 0, g_lpMyFunc, NULL, 0, NULL);
}

, : g_lpMyFunc NULL, hProcess ( ), , g_lpMyFunc.

, , CreateRemoteThread ( , ), , , DWORD.

Initialize/Uninitialize , , DLL ++/CLI.

, , . .

+3

All Articles