CreateRemoteThread导致进程崩溃无错误代码

CreateRemoteThread causes process to crash without error code

我正在尝试在另一个进程(“宿主”)中执行一个简单的函数。为此,我调用 WriteProcessMemory 将函数复制到主机,然后使用 CreateRemoteThread 来执行该函数。主机进程刚刚崩溃,没有错误代码。

我使用 Notepad++(32 位)作为示例主机。我还将我的程序编译为 x86(显然在 Windows 上)。我在这里做错了什么?

#include <iostream>
#include <Windows.h>
#include <psapi.h>

// the function to be executed inside the host
DWORD __stdcall func(LPVOID pParam)
{
    // this is the end goal, but
    // just return 1 for now to help
    // solve one problem at a time
    /*
    AllocConsole(); FILE* consoleFile;
    freopen_s(&consoleFile, "CONOUT$", "w", stdout);

    int parameter = *(int*)pParam;
    std::cout << "param: " << parameter << std::endl;
    */
    return 1;
}

// exists only to help calculate the size of func()
DWORD __stdcall after()
{
    return 0;
}

int main() {
    HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 30512); // PID found via task manager
    char procName[MAX_PATH + 1];
    GetModuleFileNameEx(process, NULL, procName, MAX_PATH);
    std::cout << "got process: " << procName << std::endl;

    size_t functionSize = (DWORD)after - (DWORD)func;
    void* functionMemory = VirtualAllocEx(process, NULL, functionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    std::cout << "function address: " << (DWORD)functionMemory << std::endl;
    bool functionWPM = WriteProcessMemory(process, functionMemory, func, functionSize, NULL);
    std::cout << "function wpm: " << (functionWPM ? "true" : "false") << std::endl;

    int parameter = 1234;
    size_t parameterSize = sizeof(int);
    void* parameterMemory = VirtualAllocEx(process, NULL, parameterSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    std::cout << "parameter address: " << (DWORD)parameterMemory << std::endl;
    bool parameterWPM = WriteProcessMemory(process, parameterMemory, &parameter, parameterSize, NULL);
    std::cout << "parameter wpm: " << (parameterWPM ? "true" : "false") << std::endl;

    
    HANDLE hThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)functionMemory, parameterMemory, 0, NULL);
    WaitForSingleObject(hThread, INFINITE);
    std::cout << "thread 0x" << std::hex << hThread << std::dec << " completed" << std::endl;

    std::cout << "errno: " << GetLastError() << std::endl;

    CloseHandle(hThread);
    CloseHandle(process);
    return 0;
}

这是输出,并不表示出现任何问题:

got process: C:\Program Files (x86)\Notepad++\notepad++.exe
function address: 55115776
function wpm: true
parameter address: 55181312
parameter wpm: true
(there is a noticable ~0.5 second delay here)
thread 0x000000E0 completed
errno: 0

当前问题的解决方案是在发布模式下编译。我不确定为什么,所以如果有人有想法,我很乐意在评论中听到它。

正如@RaymodChen 所提到的,这个过程比我想象的要复杂,我无法运行 主机进程中的任何大量代码。

如果有人遇到这个问题并试图做同样的事情,我的建议是记住 func() 的地址 space 与您的注入程序完全不同。这意味着如果你想调用 AllocConsole() 那么你必须确定它在主机程序中的地址,然后在该地址调用它而不是像我在问题中所做的那样只使用 AllocConsole()