【发布时间】:2020-04-01 04:09:48
【问题描述】:
我在这个小程序中尝试对 CreateFile 进行 Detours 钩子时遇到了一些麻烦:
#include <windows.h>
#include <iostream>
int main(HINSTANCE hinst, HINSTANCE hPrevInstance, LPSTR cmdLine, int showCmd)
{
HANDLE file;
DWORD bytesRead, bytesWritten, pos;
TCHAR msg[1000];
std::cout << "Start creating file \"SampleFile.txt\"" << std::endl;
file = CreateFile(L"C:\\TestHook\\SampleFile.txt", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
std::cout << "\"SampleFile.txt\" added into C folder" << std::endl;
CloseHandle(file);
return 0;
}
应用了一个DLL:
#include<windows.h>
#include<windows.h>
#include "C:\Detours\Detours-4.0.1\include\detours.h"
static HANDLE(WINAPI* TrueCreateFile)(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile) = CreateFileW;
__declspec(dllexport) HANDLE WINAPI MyCreateFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD
dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
HANDLE hookFile = CreateFile(L"C:\\TestHook\\hookYouGo.txt", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
std::cout << "CreateFile() is hooked...Meet other file name than you want" << std::endl;
CloseHandle(hookFile);
return hookFile;
}
BOOL WINAPI DLLMain(HINSTANCE hinst, DWORD reason_for_call, LPVOID lpReserved)
{
std::cout << "test" << std::endl;
if (reason_for_call = DLL_PROCESS_ATTACH)
{
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)TrueCreateFile, MyCreateFile);
DetourTransactionCommit();
}
return TRUE;
}
在 Visual Studio '19 (OS Windows 10) 中执行后,它会在目标文件夹中添加一个新文件,但超出我的预期。代替 hookYouGo.txt,SampleHook.txt 出现在那里,就好像钩子附件失败一样。在进程完成后查看 API 监视器,我没有发现任何证据表明 DLL 也被有序应用。在命令行中,它是一样的,因为我启动 withdll.exe 运行到输出,如 SampleFile 上的语句,但 DLL 的东西似乎超出了这个过程。 withdll.exe 和 main func 程序和 DLL 都在同一个文件夹中,当然。
【问题讨论】:
-
你的钩子函数不是调用原始函数(
TrueCreateFile),它是递归调用钩子函数。很惊讶它并没有以堆栈溢出结束。