Search code examples
c++hookdriverswindows-kerneleasyhook

Calling NtQuerydirectoryFile from a Kernel Hook Crashes the Kernel


I'm using the latest version of EasyHook to hook some kernel functions. I did setup a debugging important successfully on a Windows 8.1 64-bit based virtual machine, and I tested hooking both of NtQuerydirectoryFile and NtQuerySystemInformation in user mode and NtQuerySystemInformation in kernel mode without any problem.

My current problem is hooking NtQuerydirectoryFile using the same code that I used for the user mode hook, but it fails when I call the original function giving me an access violation error. I'm using the following code for the kernel mode hook:

NTSTATUS NtQueryDirectoryFile_Hook(
    __in HANDLE FileHandle,
    __in_opt HANDLE Event,
    __in_opt PIO_APC_ROUTINE ApcRoutine,
    __in_opt PVOID ApcContext,
    __out PIO_STATUS_BLOCK IoStatusBlock,
    __out_bcount(Length) PVOID FileInformation,
    __in ULONG Length,
    __in FILE_INFORMATION_CLASS FileInformationClass,
    __in BOOLEAN ReturnSingleEntry,
    __in PUNICODE_STRING FileName OPTIONAL,
    __in BOOLEAN RestartScan
    )
{
    NTSTATUS status;
    status = NtQueryDirectoryFile(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, FileInformation, Length, FileInformationClass, ReturnSingleEntry, FileName, RestartScan);
    return status;
}

Solution

  • As I mentioned before, the original trampoline jump modified the RAX register, so I replaced it with another trampoline:

    50                             push   rax
    48 b8 00 00 00 00 00 00 00 00  mov rax, 0x0
    48 87 04 24                    xchg   QWORD PTR [rsp],rax
    c3                             ret
    

    In addition to fixing the function that rely on hard-coded size of the trampoline jump code since the newer version is bigger. Now it's working without any problem.