c++无痕HOOK方式=硬断+VEH

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
BOOL APIENTRY DllMain( HMODULE hModule,DWORD  ul_reason_for_call, LPVOID lpReserved )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        {
            AddVectoredExceptionHandler(1, (PVECTORED_EXCEPTION_HANDLER)ExceptionHandler);
            SetHwBreakpoint();
        }
    case DLL_THREAD_ATTACH:
        {
            SetHwBreakpoint();
        }
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

void SetHwBreakpoint()
{
    CONTEXT ctx;
    ctx.ContextFlags = CONTEXT_ALL;
    GetThreadContext(GetCurrentThread(), &ctx);
    ctx.Dr0 = 0x6f3a20dd;
    ctx.Dr1 = 0x6f361f7b;
    ctx.Dr7 = 0x405;
    SetThreadContext(GetCurrentThread(), &ctx);
}

DWORD NTAPI ExceptionHandler(EXCEPTION_POINTERS * ExceptionInfo)
{
    if ((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress == 0x6f3a20dd)
    {
        //直接改eip模拟jmp
        ExceptionInfo->ContextRecord->Eip += 0x34;
        return EXCEPTION_CONTINUE_EXECUTION;
    }
    else if ((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress == 0x6f361f7b)
    {
        //直接设eax为零模拟mov eax,0
        ExceptionInfo->ContextRecord->Eax = 0;
        ExceptionInfo->ContextRecord->Eip += 5;
        return EXCEPTION_CONTINUE_EXECUTION;
    }
    else
    {
        //在异常handler里重设drx防止断点被意外清除
        ExceptionInfo->ContextRecord->Dr0 = 0x6f3a20dd;
        ExceptionInfo->ContextRecord->Dr1 = 0x6f361f7b;
        ExceptionInfo->ContextRecord->Dr7 = 0x405;
        return EXCEPTION_CONTINUE_SEARCH;
    }
}