CreateRemoteThread does not work with DLL

269 Views Asked by At

I am trying to inject a simple dll that creates a MessageBox in the target process. Using a injector from the www works without any issues. However using my own code to inject does not do anything at all (I am using it on notepad.exe)

I compiled both dll and this code as x64 debug in VS2017. Injector is created as Win32 console project.

All the stages in the code passes. I get a handle to the process and also the thread handle is valid. However the GetExitCode returns 0 so it fails all the time but I do not know why?

    HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, false, pid);

if (process == NULL)
{
    std::cout << "Error opening process." << std::endl;
    return false;
}

const char * dllString = "C:\\test.dll";

// load memory for dll

int bytes = sizeof(dllString);


PVOID mem = VirtualAllocEx(process, NULL, sizeof(dllString) + 1, MEM_COMMIT, PAGE_READWRITE);

if (mem == NULL)
{
    std::cout << "Unable to allocate mem." << std::endl;
    CloseHandle(process);
    return false;
}

// write dll path to that location
SIZE_T bytesWritten;
BOOL status = WriteProcessMemory(process, mem, dllString, sizeof(dllString) + 1, &bytesWritten);

if (!status)
{
    std::cout << "Writing dll path failed." << std::endl;
    VirtualFreeEx(process, mem, sizeof(dllString) + 1, MEM_RELEASE);
    CloseHandle(process);
    return false;
}

FARPROC loadLibrary = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

HANDLE thread = CreateRemoteThread(process, NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(loadLibrary), mem, NULL, NULL);

if (thread == INVALID_HANDLE_VALUE)
{
    std::cout << "Unable to create thread in remote process. " << std::endl;
    VirtualFreeEx(process, mem, sizeof(dllString) + 1, MEM_RELEASE);
    CloseHandle(process);
}


WaitForSingleObject(thread, INFINITE);

DWORD exitCode = 0;
GetExitCodeThread(thread, &exitCode);

if (exitCode != 0)
    std::cout << "DLL loaded successfully." << std::endl;
else
    std::cout << "DLL loading failed." << std::endl;

CloseHandle(thread);
VirtualFreeEx(process, mem, sizeof(dllString) + 1, MEM_RELEASE);
CloseHandle(process);
return true;
1

There are 1 best solutions below

0
On

Just solved it myself. Actually a noob issue. sizeof in fact is returning the size of the pointer with is 64bits for x64 and not the length of the string for the memory I needed to allocate. So after changing it to strlen it worked.