x64 crash?

Mar 25, 2010 at 1:06 PM

This code silently terminates when original closesocket() is called, i.e. after first message box. So far happens on 64-bit XP only. When I change winsock2.h to winsock.h, it works.

Am I doing something wrong? Do I call original function correctly? There is unmanaged sample, but it does not seem to call original code of MessageBeep() from hook proc.

#define _WIN32_WINNT 0x501

#include <winsock2.h>
#include <windows.h>
#include <Winternl.h>
#include <stdio.h>
#pragma warning(disable: 4005)
#include <ntstatus.h>
#pragma warning(default: 4005)
#include "easyhook.h"

#pragma comment (lib, "easyhook64.lib")
#pragma comment (lib, "psapi")

typedef int (WINAPI * Fn_closesocket)(SOCKET s);
int WINAPI Mine_closesocket(SOCKET s)
{
    static int (WINAPI * Real_closesocket)(SOCKET s) = (Fn_closesocket) GetProcAddress(GetModuleHandle("ws2_32"), "closesocket");
    MessageBox(0, "closesocket hooked.\n", 0, 0);
    int rv = Real_closesocket(s);
    MessageBox(0, "closesocket still hooked.\n", 0, 0);
    return rv;
}

EASYHOOK_BOOL_EXPORT EasyHook_Init(HMODULE hModule);
EASYHOOK_EXPORT EasyHook_ThreadUninit();
EASYHOOK_EXPORT EasyHook_Uninit();

int main()
{
    HOOK_TRACE_INFO hook = {0};

    EasyHook_Init(GetModuleHandle(0));

    printf("Begin.\n");
    
    NTSTATUS status = LhInstallHook(closesocket, Mine_closesocket, (PVOID)0x12345678, &hook);
    printf("LhInstallHook=%08X\n", status);
    if (status == STATUS_SUCCESS)
    {
        ULONG acl;
        status = LhSetExclusiveACL(&acl, 0, &hook);
        printf("LhSetExclusiveACL=%08X\n", status);
    }

    printf("Test.\n");

    closesocket(0);

    printf("End.\n");
}

Jul 26, 2010 at 10:34 AM
Edited Jul 26, 2010 at 10:36 AM

The problem is that the function LhRelocateEntryPoint in reloc.c does not handle the mov instruction correctly.

Original entry point

000007FF77152C70 sub rsp,48h (48 83 ec 48) 
000007FF77152C74 mov rax,qword ptr [7FF77177440h] (48 8b 05 c5 47 02 00) 
000007FF77152C7B mov qword ptr [rsp+58h],rbx 

Relocated entry point

000007FF77180498 sub rsp,48h (48 83 ec 48) 
000007FF7718049C mov rax,qword ptr [7FF771A4C68h] (48 8b 05 c5 47 02 00) 
000007FF771804A3 jmp 000007FF77152C7B 

An adjusted offset for the mov instruction should be calculated.