jjzjj

c++ - Windows API 钩子(Hook) C++

coder 2024-06-09 原文

我正在学习为 Windows API 编写 Hook ,为了练习,我正在为 pDeleteFileA 函数编写 Hook 。当调用该函数时,在删除文件之前我想检查文件名是否为“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;
}

最佳答案

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

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

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

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

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

编辑:更多注释。您正在尝试 Hook DeleteFileA,它是 ASCII 版本,较新的软件将改用 DeleteFileW

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

关于c++ - Windows API 钩子(Hook) C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36664116/

有关c++ - Windows API 钩子(Hook) C++的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  3. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  4. ruby-on-rails - 在所有延迟的作业之前 Hook - 2

    是否可以在所有delayed_job任务之前运行一个方法?基本上,我们试图确保每个运行delayed_job的服务器都有我们代码的最新实例,所以我们想运行一个方法来在每个作业运行之前检查它。(我们已经有了“check”方法并在别处使用它。问题只是关于如何从delayed_job中调用它。) 最佳答案 现在有一种官方方法可以通过插件来做到这一点。这篇博文通过示例清楚地描述了如何执行此操作http://www.salsify.com/blog/delayed-jobs-callbacks-and-hooks-in-rails(本文中描述

  5. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  6. ruby - 刚刚分配的变量是否有 ruby 钩子(Hook)? - 2

    这是我理想中想要的。用户做:a="hello"输出为Youjustallocated"a"!=>"Hello"顺序无关紧要,只要我能实现该消息即可。 最佳答案 不,没有直接的方法可以做到这一点,因为在执行代码之前,Ruby字节码编译器会丢弃局部变量名。YARV(MRI1.9.2中使用的RubyVM)提供的关于局部变量的唯一指令是getlocal和setlocal,它们都对整数索引进行操作,而不是变量名。以下是1.9.2源代码中insns.def的摘录:/****************************************

  7. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

  8. ruby - Sinatra + Heroku + Datamapper 使用 dm-sqlite-adapter 部署问题 - 2

    出于某种原因,heroku尝试要求dm-sqlite-adapter,即使它应该在这里使用Postgres。请注意,这发生在我打开任何URL时-而不是在gitpush本身期间。我构建了一个默认的Facebook应用程序。gem文件:source:gemcuttergem"foreman"gem"sinatra"gem"mogli"gem"json"gem"httparty"gem"thin"gem"data_mapper"gem"heroku"group:productiondogem"pg"gem"dm-postgres-adapter"endgroup:development,:t

  9. ruby - Ruby 中字符串运算符 + 和 << 的区别 - 2

    我是Ruby和这个网站的新手。下面两个函数是不同的,一个在函数外修改变量,一个不修改。defm1(x)x我想确保我理解正确-当调用m1时,对str的引用被复制并传递给将其视为x的函数。运算符当调用m2时,对str的引用被复制并传递给将其视为x的函数。运算符+创建一个新字符串,赋值x=x+"4"只是将x重定向到新字符串,而原始str变量保持不变。对吧?谢谢 最佳答案 String#+::str+other_str→new_strConcatenation—ReturnsanewStringcontainingother_strconc

  10. ruby - rails 3.2.2(或 3.2.1)+ Postgresql 9.1.3 + Ubuntu 11.10 连接错误 - 2

    我正在使用PostgreSQL9.1.3(x86_64-pc-linux-gnu上的PostgreSQL9.1.3,由gcc-4.6.real(Ubuntu/Linaro4.6.1-9ubuntu3)4.6.1,64位编译)和在ubuntu11.10上运行3.2.2或3.2.1。现在,我可以使用以下命令连接PostgreSQLsupostgres输入密码我可以看到postgres=#我将以下详细信息放在我的config/database.yml中并执行“railsdb”,它工作正常。开发:adapter:postgresqlencoding:utf8reconnect:falsedat

随机推荐