#include <windows.h> #include <stdio.h>

// 定义NtWriteFile函数指针 typedef NTSTATUS(WINAPI *NtWriteFileFunc)(HANDLE FileHandle, HANDLE Event, PVOID ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, PLARGE_INTEGER ByteOffset, PULONG Key);

// 定义全局变量,用于保存原始NtWriteFile函数指针 NtWriteFileFunc g_originalNtWriteFile = NULL;

// 定义我们的NtWriteFile函数,作为APIHOOK NTSTATUS WINAPI MyNtWriteFile(HANDLE FileHandle, HANDLE Event, PVOID ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, PLARGE_INTEGER ByteOffset, PULONG Key) { // 输出参数 char msg[1024]; sprintf_s(msg, 1024, 'MyNtWriteFile called, FileHandle=%p, Buffer=%p, Length=%u\n', FileHandle, Buffer, Length); OutputDebugStringA(msg);

// 调用原始NtWriteFile函数
return g_originalNtWriteFile(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, Buffer, Length, ByteOffset, Key);

}

// 安装APIHOOK BOOL InstallApiHook() { // 获取ntdll.dll模块句柄 HMODULE ntdllModule = GetModuleHandleA('ntdll.dll'); if (ntdllModule == NULL) { OutputDebugStringA('GetModuleHandleA failed\n'); return FALSE; }

// 获取NtWriteFile函数地址
g_originalNtWriteFile = (NtWriteFileFunc)GetProcAddress(ntdllModule, 'NtWriteFile');
if (g_originalNtWriteFile == NULL)
{
    OutputDebugStringA('GetProcAddress failed\n');
    return FALSE;
}

// 修改NtWriteFile函数的内存页属性,使其可写
DWORD oldProtect = 0;
if (!VirtualProtect(g_originalNtWriteFile, sizeof(NtWriteFileFunc), PAGE_EXECUTE_READWRITE, &oldProtect))
{
    OutputDebugStringA('VirtualProtect failed\n');
    return FALSE;
}

// 覆盖NtWriteFile函数地址,使其指向我们的MyNtWriteFile函数
*(NtWriteFileFunc*)g_originalNtWriteFile = MyNtWriteFile;

// 恢复NtWriteFile函数的内存页属性
if (!VirtualProtect(g_originalNtWriteFile, sizeof(NtWriteFileFunc), oldProtect, &oldProtect))
{
    OutputDebugStringA('VirtualProtect failed\n');
    return FALSE;
}

return TRUE;

}

// 卸载APIHOOK BOOL UninstallApiHook() { // 修改NtWriteFile函数的内存页属性,使其可写 DWORD oldProtect = 0; if (!VirtualProtect(g_originalNtWriteFile, sizeof(NtWriteFileFunc), PAGE_EXECUTE_READWRITE, &oldProtect)) { OutputDebugStringA('VirtualProtect failed\n'); return FALSE; }

// 恢复NtWriteFile函数地址,使其指向原始函数
*(NtWriteFileFunc*)g_originalNtWriteFile = g_originalNtWriteFile;

// 恢复NtWriteFile函数的内存页属性
if (!VirtualProtect(g_originalNtWriteFile, sizeof(NtWriteFileFunc), oldProtect, &oldProtect))
{
    OutputDebugStringA('VirtualProtect failed\n');
    return FALSE;
}

return TRUE;

}

// DLL入口函数 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: if (!InstallApiHook()) { OutputDebugStringA('InstallApiHook failed\n'); return FALSE; } break;

case DLL_PROCESS_DETACH:
    if (!UninstallApiHook())
    {
        OutputDebugStringA('UninstallApiHook failed\n');
        return FALSE;
    }
    break;

default:
    break;
}

return TRUE;

}

C语言实现NtWriteFile API HOOK并使用OutputDebugStringA输出参数

原文地址: https://www.cveoy.top/t/topic/muUJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录