挂起CreateFile抛出异常:读取访问冲突

时间:2018-04-30 19:36:43

标签: c++ exception hook

当我运行我的程序时,它成功地创建了文件,但当我尝试将我的CreateFile API注入我的程序时,它显示异常

   Exception thrown: read access violation.

   pbCode was nullptr.

我从各个网站搜索但仍无法找到问题 这是钩子CreateFile的代码

_CreateFile TrueCreateFile = 
(_CreateFile)GetProcAddress(GetModuleHandle(L"kernel32"), "CreateFile");
HANDLE WINAPI HookCreateFile(
_In_     LPCTSTR               lpFileName,
_In_     DWORD                 dwDesiredAccess,
_In_     DWORD                 dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_     DWORD                 dwCreationDisposition,
_In_     DWORD                 dwFlagsAndAttributes,
_In_opt_ HANDLE                hTemplateFile)
   {    

      HANDLE out = TrueCreateFile((LPCTSTR)"C:\\Users\\abc\\bar.txt",
      dwDesiredAccess,
      dwShareMode,
      lpSecurityAttributes,
      dwCreationDisposition,
      dwFlagsAndAttributes,
      hTemplateFile);

return out;
}

挂钩CreateFile

void hook_CreateFile()
{
   HANDLE hProc = NULL;
   if (Mhook_SetHook((PVOID*)&TrueCreateFile, HookCreateFile)) {
    // Now call OpenProcess and observe NtOpenProcess being redirected
    // under the hood.
    hProc = OpenProcess(PROCESS_ALL_ACCESS,
        FALSE, GetCurrentProcessId());
    if (hProc) {
        printf("Successfully opened CreateFile: %p\n", hProc);
        CloseHandle(hProc);
    }
    else {
        printf("Could not open CreateFile: %d\n", GetLastError());
         }
    }
   }

1 个答案:

答案 0 :(得分:0)

TrueCreateFile是指向函数地址的指针。

您正在传递&TrueCreateFile,它是指针的地址。

您要钩住指针而不是函数。

只需通过(void*)TrueCreateFile