Hooking already running process using MS Detours

Viewed 51

Is it possible to hook a process that already is running using Microsoft Detours? The samples create a target process and modify it.

So, I tried to write something similar but for a running process.

I used DetourCreateProcessWithDllExW() (creatwth.cpp) as the base for my trials and wrote a procedure that OpenProcess() instead of CreateProcess(), almost all the other logic is the same. The code runs smoothly and does all the steps just like DetourCreateProcessWithDllExW() do, but no hooking occurs as well as I don't see the DLL injected in the target app (looking using SysInternals Process Explorer).

My code:

typedef LONG(NTAPI* NtSuspendProcess)(IN HANDLE ProcessHandle);
typedef LONG(NTAPI* NtResumeProcess)(IN HANDLE ProcessHandle);

HANDLE WINAPI DetourAttachToProcessDll(_In_ DWORD dwTargetPid,
                              _In_ DWORD dwDesiredAccess,
                              _In_ BOOL bInheritHandles,
                              _In_ LPCSTR lpDllName,
                              _In_opt_ PDETOUR_OPEN_PROCESS_ROUTINE pfOpenProcess)
{
    if (pfOpenProcess == NULL) {
        pfOpenProcess = OpenProcess;
    }

    NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(GetModuleHandle("ntdll"), "NtSuspendProcess");
    NtResumeProcess pfnNtResumeProcess = (NtResumeProcess)GetProcAddress(GetModuleHandle("ntdll"), "NtResumeProcess");

    HANDLE hProcess = pfOpenProcess(dwDesiredAccess, bInheritHandles, dwTargetPid);
    if (!hProcess) {
        return NULL;
    }

    pfnNtSuspendProcess(hProcess);

    if (!DetourUpdateProcessWithDll(hProcess, &lpDllName, 1) &&
        !DetourProcessViaHelperA(dwTargetPid, lpDllName, CreateProcessA)) {
        CloseHandle(hProcess);
        return NULL;
    }

    pfnNtResumeProcess(hProcess);

    return hProcess;
}

As you can see, it consumes PID and desired access flags that equal PROCESS_ALL_ACCESS for the tests.

Thank you!

0 Answers
Related