【问题标题】:Windows API Hook C++Windows API 挂钩 C++
【发布时间】:2016-08-08 10:16:39
【问题描述】:

我正在学习为 Windows API 编写钩子,为了练习,我正在为 pDeleteFileA 函数编写一个钩子。当函数将被调用时,在删除文件之前,我想检查文件名是否为“testfile.txt”,如果是,则不会删除它,而是会弹出一条消息,如果它调用了其他内容,则继续删除文件。

我已经编写了一些代码,并且代码编译没有任何错误,但是当我尝试删除“testfile.txt”时,它只是被删除了。也许有人可以给我提示我做错了什么或我没有做什么?

到目前为止,这是我的代码:

#include <Windows.h>

struct hook_t{// a datatype to store information about our hook
    bool isHooked = false;
    void* FunctionAddress = operator new(100);
    void* HookAddress = operator new(100);
    char Jmp[6] = { 0 };
    char OriginalBytes[6] = {0};
    void* OriginalFunction = operator new(100);
};

namespace hook {
    bool InitializeHook(hook_t* Hook, char* Module, char* Function, void* HookFunction) {
        HMODULE hModule;
        DWORD OrigFunc, FuncAddr;
        byte opcodes[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0xe9, 0x00, 0x00, 0x00, 0x00};
        if (Hook->isHooked) {
            return false;
        }

        hModule = GetModuleHandleA(Module);
        if (hModule == INVALID_HANDLE_VALUE) {
            Hook->isHooked = false;
            return false;
        }

        Hook->Jmp[0] = 0xe9;
        *(PULONG)&Hook->Jmp[1] = (ULONG)HookFunction - (ULONG)Hook->FunctionAddress - 5;
        memcpy(Hook->OriginalBytes, Hook->FunctionAddress, 5);
        Hook->OriginalFunction = VirtualAlloc(0, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        if (Hook->OriginalFunction == NULL) {
            return false;
        }
        memcpy(Hook->OriginalFunction, Hook->OriginalBytes, 5);
        OrigFunc = (ULONG)Hook->OriginalFunction + 5;
        FuncAddr = (ULONG)Hook->OriginalFunction + 5;
        *(LPBYTE)((LPBYTE)Hook->OriginalFunction + 5) = 0xe9;
        *(PULONG)((LPBYTE)Hook->OriginalFunction + 6) = (ULONG)FuncAddr;
        Hook->isHooked = true;
        return true;

    }//end InitializeHook

    bool InsertHook(hook_t* Hook) {
        DWORD op;
        if (!Hook->isHooked) {
            return false;
        }
        VirtualProtect(Hook->FunctionAddress, 5, PAGE_EXECUTE_READWRITE, &op);
        memcpy(Hook->FunctionAddress, Hook->Jmp, 5);
        VirtualProtect(Hook->FunctionAddress, 5, op, &op);
        return true;
    }

    bool Unhook(hook_t* Hook) {
        DWORD op;
        if (!Hook->isHooked) {
            return false;
        }
        VirtualProtect(Hook->FunctionAddress, 5, PAGE_EXECUTE_READWRITE, &op);
        memcpy(Hook->FunctionAddress, Hook->OriginalBytes, 5);
        VirtualProtect(Hook->FunctionAddress, 5, op, &op);
        Hook->isHooked = false;
        return true;
    }

    bool FreeHook(hook_t* Hook) {
        if (Hook->isHooked) {
            return false;
        }
        VirtualFree(Hook->OriginalFunction, 0, MEM_RELEASE);
        memset(Hook, 0, sizeof(hook_t*));
        return true;
    }

}//end namespase

==========================================================================

#define _CRT_SECURE_NO_WARNINGS

#include "apihook.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace hook;

//define the function to be hooked
typedef BOOL(WINAPI* pDeleteFileA)(LPCSTR lpFileName);//in this case this will be delete file a

pDeleteFileA pDeleteFile;//instance of it
hook_t* Hook = new hook_t();

//this function will replace the original API function in the process
BOOL WINAPI HookDeleteFileA(LPCSTR lpFileName) {
    //we can do here whatever we want before the original API function is called
    //for example disable deleting of a certain file
    if (strstr(lpFileName, "testfile")) {//checks if parameter contains a string
        //disable deleting of this file
        SetLastError(ERROR_ACCESS_DENIED);
        MessageBoxA(0, "You can't delete this file!", "error", 0);
        return false;
    }
    return pDeleteFile(lpFileName);//if parameter does not contain our string, call the original API function
}

void StartRoutine() {
    pDeleteFile = (pDeleteFileA)&Hook->OriginalFunction;
    //the pDeleteFileA is located in "kernel32.dll"
    InitializeHook(Hook, "kernel32.dll", "DeleteFileA", HookDeleteFileA);
    InsertHook(Hook);//spawn the hook to the current process
}

BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {
    switch (dwReason) {
    case DLL_PROCESS_ATTACH:
        printf("API Hook Attached!");//notify
        StartRoutine();
        break;
    case DLL_PROCESS_DETACH:
        Unhook(Hook);//unhook the hook
        FreeHook(Hook);//remove the hook from memory
    }
}

int main() {

    HMODULE hModule = GetModuleHandleA("kernel32.dll");

    //The reason code that indicates why the DLL entry-point function is being called.
    //This parameter can be one of the following values:
    //DLL_PROCESS_ATTACH 1:
    //The DLL is being loaded into the virtual address space of the current process 
    //as a result of the process starting up or as a result of a call to LoadLibrary. 
    //DLL_PROCESS_DETACH 0:
    //The DLL is being unloaded from the virtual address space of the calling process 
    //because it was loaded unsuccessfully or the reference count has reached zero 
    //(the processes has either terminated or called FreeLibrary one time for each time it called LoadLibrary).
    DWORD dwReason = DLL_PROCESS_ATTACH;


    //If fdwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads
    //If fdwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if FreeLibrary has been called or the DLL load 
    //failed and non-NULL if the process is terminating.
    LPVOID lpReserved = NULL;

    DllMain(hModule, dwReason, lpReserved);

    return 0;
}

【问题讨论】:

  • 你是在挂钩自己的进程并在资源管理器中删除文件吗?
  • 是的,这是我的第一个钩子,如果我做错了,你能给我一些建议吗?
  • 是的,这行不通。您为自己的进程挂钩了 DeleteFileA,因此要对资源管理器产生任何影响,资源管理器本身应该已经加载了这个 dll,这显然不会发生。另外,main() exe 入口点中的 DllMain 是怎么回事?

标签: c++ windows winapi hook system-calls


【解决方案1】:

每个进程都有自己的地址空间。

每个进程单独加载它的 DLL 并拥有单独的内存。因此,如果您尝试覆盖内存 - 您只是覆盖了加载到您的进程中的 DLL 副本。这样做是出于稳定性和安全性的原因。

要在另一个进程中写入内存并执行代码 - 你需要使用DLL Injection,wiki 对场景和方法有很好的概述。

所以你需要把你的代码放到 DLL 中,然后把这个 DLL 加载到目标进程中。然后你的 DLL 在它的 DLLMain 中会覆盖这个进程的函数(钩子代码)。这也意味着挂钩代码将在挂钩进程的上下文中运行,因此 MessageBox 或 printf 可能无法按预期工作。

另外我强烈建议使用第二台带有远程调试或虚拟机的 PC,因为挂钩系统进程可能会导致不稳定。

编辑:更多注释。您正在尝试挂钩 DeleteFileA,这是 ASCII 版本,而较新的软件将使用 DeleteFileW

Edit2:您也不能将 32 位 DLL 加载到 64 位进程中,反之亦然。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多