c++ - Hook sendto() 会导致崩溃,具体取决于代码顺序

标签 c++ windows hook dll-injection

我正在使用 DLL 注入(inject)器注入(inject)一个 dll,它进入 IAT 并用我自己的替换系统调用 sendto()。

这是替换方法。

void replaceFunction(DWORD f, DWORD nf)
{
// Base address.
HMODULE hMod = GetModuleHandle(NULL);

// DOS Header.
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)hMod;

// NT Header.
PIMAGE_NT_HEADERS ntHeader = MakePtr(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);

// Import Table descriptor.
PIMAGE_IMPORT_DESCRIPTOR importDesc = MakePtr(PIMAGE_IMPORT_DESCRIPTOR, dosHeader,ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);

// Make writeable.
removeReadOnly(MakePtr(PIMAGE_THUNK_DATA, hMod, importDesc->FirstThunk));

while(importDesc->Name)
{
    PIMAGE_THUNK_DATA pThunk = MakePtr(PIMAGE_THUNK_DATA, dosHeader, importDesc->FirstThunk);

    while (pThunk->u1.Function)
    {
        if(pThunk->u1.Function == f)
        {
            pThunk->u1.Function = nf;
        }
        pThunk++;
    }

    importDesc++;
}
}

调用者:

// Get the Function Address
DWORD f = (DWORD)GetProcAddress(GetModuleHandleA("ws2_32.dll"),"sendto");
DWORD nf = (DWORD)&my_sendto;

// Save real sendto address.
real_sendto = (int (*)(SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen))f;

// Replace function.
replaceFunction(f, nf);

这个有效:

int my_sendto(SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen)
{
    CreateThread(NULL, 0, de_sendto, NULL, 0, NULL);
    return real_sendto(s, buf, len, flags, to, tolen);
}

有效:

int my_sendto(SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen)
{
    int l = real_sendto(s, buf, len, flags, to, tolen);
    CreateThread(NULL, 0, de_sendto, NULL, 0, NULL);
    return l;
}

使用后一版本的 my_sendto() 后,主机应用程序将在调用 sendto() 时崩溃。

de_sendto 定义为:

DWORD WINAPI de_sendto(LPVOID args) { }

最佳答案

您的调用约定不正确。 C++默认的调用约定是__cdecl,而sendto的调用约定是__stdcall。将 my_sendto 的调用约定更改为 __stdcall 以修复崩溃。

关于c++ - Hook sendto() 会导致崩溃,具体取决于代码顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6949560/

相关文章:

c++ - 静态与成员运算符重载:std::operator<< 和 std::ostream::operator<<

c++ - Qt Creator 中的运行按钮被禁用

javascript - JQuery/Javascript Hook

ios - 如何 Hook 私有(private)框架

c++ - 为什么摆脱 volatile 是危险的?

c++ - 为什么模板类型参数不可见/不存在而不是非类型参数?

c++ - 由于未对齐的内存地址,内存地址是否会被破坏?

c++ - 在 Windows/C++ 上控制 USB TMC 设备的最简单方法

.net - Perfmon、PerfMonitor 和 PerfView

c++ - 防止 Qt 窗口在 Hook 的应用程序中关闭,Eventfilter 不执行任何操作