将非Windows API函数与弯路挂钩

时间:2019-06-30 22:09:30

标签: x86 hook calling-convention detours

我想将非Windows api函数挂接到可执行文件中(一次-不是永久的),我使用调试器找到了函数地址(0x2bf2ca5),我在使用以下代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>
#include "detours.h"
#include <stdint.h>

#pragma comment(lib, "detours.lib")

static int(*TrueFunc)(int unk1, int unk2, uint8_t unk3, uint8_t unk4, uint8_t unk5, uint8_t unk6, uint8_t unk7, uint8_t unk8, uint8_t unk9, uint8_t unk10, int unk11, int unk12, int unk13, int unk14) = (int(*)(int unk1, int unk2, uint8_t unk3, uint8_t unk4, uint8_t unk5, uint8_t unk6, uint8_t unk7, uint8_t unk8, uint8_t unk9, uint8_t unk10, int unk11, int unk12, int unk13, int unk14))(0x2bf2ca5);


int Hook_TrueFunc(int unk1, int unk2, uint8_t unk3, uint8_t unk4, uint8_t unk5, uint8_t unk6, uint8_t unk7, uint8_t unk8, uint8_t unk9, uint8_t unk10, int unk11, int unk12, int unk13, int unk14)
{
    printf("%c",unk8);
    return 0;
}

BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
    LONG error;
    (void)hinst;
    (void)reserved;

    if (DetourIsHelperProcess()) {
        return TRUE;
    }

    if (dwReason == DLL_PROCESS_ATTACH) {

        DetourRestoreAfterWith();


        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourAttach(&(PVOID&)TrueFunc, Hook_TrueFunc);
        error = DetourTransactionCommit();

        if (error != NO_ERROR) {
            printf("error=%u\n", error);
        }

    }
    else if (dwReason == DLL_PROCESS_DETACH) {
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourDetach(&(PVOID&)TrueFunc, Hook_TrueFunc);
        error = DetourTransactionCommit();

    }
    return TRUE;
}

该函数的参数是这样传递的:

push    3Ch
mov     ecx, [ebp+arg_8]
push    ecx
mov     edx, [ebp+arg_4]
push    edx
push    0
sub     esp, 10h
mov     eax, esp
mov     ecx, [ebp+var_10]
mov     [eax], ecx
mov     edx, [ebp+var_C]
mov     [eax+4], edx
mov     ecx, [ebp+var_8]
mov     [eax+8], ecx
mov     edx, [ebp+var_4]
mov     [eax+0Ch], edx
push    16
mov     eax, [ebp+arg_0]
push    eax
call    Func           

我从弯路DetourTransactionCommit()得到的错误是:

#define ERROR_INVALID_PARAMETER          87L

知道我在做什么错吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

除非您已使用ASLR链接器选项关闭了ASLR或在其中打开了ASLR,否则您不应像这样对函数地址进行硬编码,因为每次运行时该地址都会因/DYNAMICBASE:NO而改变。操作系统本身。

相反,您应该使用函数名称来分配函数地址,如detour的github sample中所示,否则,您可以使用DetourFindFunction来找到函数地址,如下所示。

PVOID pfTrueFunc = DetourFindFunction("dll or exe name which has original function", "TrueFunc");
DetourAttach(&pfTrueFunc , Hook_TrueFunc);