Search code examples
windowswinapidllcode-injectiondll-injection

How to call specific function in dll injection?


Following code will inject dll and DllMain will be called. How I call specific function from 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());
    }

Solution

  • When your injected DLL's DllMain runs for the first time, call CreateThread to create a new thread that can do whatever you like. Note that you cannot call arbitrary code from DllMain as described in the documentation. Hence the call to CreateThread from DllMain.