C++ Code Injection crashes injected application

2019-07-07 04:04发布

问题:

I'm trying to inject a simple executable into another executable that I made, unfortunately, whenever I inject the code into the executable, it says 'simpleinjected.exe has stopped working' then it closes. I'm using CreateRemoteThread to inject the code. This is what I have done so far.

Injector.exe // the file that's injecting the code

#include <stdio.h>
#include <windows.h>

#define procId 2844
#define executable "executable.exe"    // located in same directory

int main()
{
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, false, procId);
    LPVOID allocated = (LPVOID)VirtualAllocEx(hProc, NULL, strlen(executable), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
    WriteProcessMemory(hProc, (LPVOID)allocated, executable, strlen(executable), NULL);
    LPVOID libaddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
    CreateRemoteThread(hProc, NULL, NULL, (LPTHREAD_START_ROUTINE)libaddr, NULL, NULL);
    CloseHandle(hProc);
    return 0;
}

Simpleinjected.exe // the file being injected

#include <stdio.h>

int main()
{
    printf("Hello");
    return 0;
}

executable.exe // the executable being injected into simpleinjected

#include <windows.h>

int main()
{
    MessageBox(NULL, "Injected successfully", "Code Injection", MB_OK);
    return 0;
}

The message is not displaying and simpleinjected.exe crashes. The crash shows that the code was inserted but I don't understand why it's crashing.

When using DLL and the same technique above, the dll executes in the 'simpleinjected.exe' but doesn't work when injected into Firefox. The dll code is below. It executes in the custom application but not Firefox even though it's injected successfully.

dllinject.dll

#include <windows.h>

int message(const char *msg)
{
    MessageBox(NULL, msg, "Message from Dll", MB_OK);
    return 0;
}

BOOL WINAPI DLLMain(HINSTANCE hInstDll, DWORD ulReason, LPVOID lpReserved)
{
    switch(ulReason)
    {
        case DLL_PROCESS_ATTACH:
            message("process attach");
            break;
        case DLL_THREAD_ATTACH:
            message("thread attach");
            break;
        case DLL_PROCESS_DETACH:
            message("process detach");
            break;
        case DLL_THREAD_DETACH:
            message("thread detach");
            break;
    }
    return true;
}

回答1:

modified code of Simpleinjected.exe as these below. and then try inject dllinject.dll to Simpleinjected.exe again.

#include <stdio.h>

int main()
{
   while(true)
   {
      printf("Hello");
   }
   return 0;
}

you should modify the defines below as same as Simpleinjected.exe.

#define procId 2844 //process id of Simpleinjected.exe
#define executable "dllinject.dll"    // located in same directory