开发者

Hooking sendto() causes crash depending on code ordering

I'm using a DLL-injector to inject a dll which goes into the IAT and replaces the system call sendto() with my own.

This is the replace method.

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++;
}
}

Called by:

// Get the Function Addre开发者_如何学运维ss
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);

This works:

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);
}

This does not work:

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;
}

Upon using the latter version of my_sendto() the host application will crash upon calling sendto().

de_sendto is defined as:

DWORD WINAPI de_sendto(LPVOID args) { }


Your calling convention is incorrect. The default calling convention for C++ is __cdecl, but sendto's calling convention is __stdcall. Change the calling convention of my_sendto to __stdcall to fix the crash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜