Microsoft Detours API hooking

181 Views Asked by At

I have a problem with MS Detours, probably doing something wrong, but not sure what.. I'm injecting the DLL into the address space of the process (this succeeds; when I monitor with process explorer and API monitor, the DLL is part of the address space of notepad.exe). Then I execute these operations in the DLL file:

#include "pch.h"
#include "detours.h"
#include "windows.h"

BOOL(WINAPI* ORIGINAL_WRITEFILE)(HANDLE, LPCVOID, //Original Function
    DWORD, LPDWORD,
    LPOVERLAPPED) = WriteFile;


BOOL WINAPI WriteFile_HOOK(HANDLE hFile, LPCVOID lpBuffer, //Hook_Function
    DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten,
    LPOVERLAPPED lpOverlapped)
{
    MessageBoxA(NULL, "HOOKED", "HOOKED", MB_OK);


    return ORIGINAL_WRITEFILE(hFile, lpBuffer, //Call original function
        nNumberOfBytesToWrite, lpNumberOfBytesWritten,
        lpOverlapped);

}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH: //Detours
        MessageBoxA(NULL, "Injected", "Injected", MB_OK);
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourAttach(&(PVOID)ORIGINAL_WRITEFILE, WriteFile_HOOK);
        if (DetourTransactionCommit() != NO_ERROR) {

            MessageBoxA(NULL, "ERROR", "ERROR", MB_OK);
        } {

            MessageBoxA(NULL, "SUCCESS", "SUCCESS", MB_OK);

        }
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

When I attach to the process and run it with a debugger, all steps are successful (also, two message boxes appear, in notepad.exe, as expected). However, when I monitor notepad.exe (with the same PID) with API monitor, it does not call the custom WriteFile function. Does anyone know what I´m doing wrong here?

enter image description here

0

There are 0 best solutions below