GithubHelp home page GithubHelp logo

hoshimin / hooklib Goto Github PK

View Code? Open in Web Editor NEW
700.0 23.0 150.0 74 KB

The functions interception library written on pure C and NativeAPI with UserMode and KernelMode support

License: MIT License

C 76.13% C++ 23.87%
x86-64 hooking hook x86 intercept-calls intercept hooklib hook-api hooks hooks-api

hooklib's Introduction

HookLib²

The Win32 lightweight functions interception library

✔ Advantages:

  • Written on pure C
  • Extremely lightweight
  • Based on the fastest and lightweight Zydis disassembler
  • Uses only NativeAPI functions
  • Has no other dependencies
  • Kernelmode support
  • Supports instructions relocation and thread's contexts fixup

📰 What's new in the 2nd Gen:

  • The HookLib was completely rewritten
  • Extremely reduced allocations, processes/threads enumerations and handles manipulations count
  • Multihook/multiunhook support that hooks/unhooks multiple functions in one session
  • Extremely reduced memory consumption for usermode hooks: one hook page (4Kb) can hold 39 cells for nearest hooks that removes the need to allocate one page per each hook
  • Support for KM->UM hooks (even with support for contexts fixup directly from kernelmode):
    • KM:Amd64 -> UM:Amd64
    • KM:Amd64 -> UM:Wow64
    • KM:i386 -> UM:i386

🔬 How it works:

TargetFunction():                                 ^ ; return
-> jmp Interceptor ------> Interceptor():         |
   ??? ; Broken bytes        ... Handler code ... |
   ... ; Continuation <--+   CallOriginal() ------|--> OriginalBeginning():
   ...         +---------|-> ...                  |      ... Original beginning ...
   ret --------+         |   ret -----------------+      ... of TargetFunction ...
                         +------------------------------ jmp Continuation

🧵 Trampolines:

Supported trampolines:

Jump to a relative offset:
E9 44 33 22 11  |  jmp rip+0x11223344 ; Relative jump to ±2Gb only

Jump to an absolute address (x32):
FF 25 44 33 22 11  | jmp ds:[0x11223344]
NN NN NN NN        | <- 0x11223344 is points to

Jump to an absolute address (x64):
FF 25 00 00 00 00        | jmp [rip+00h]
88 77 66 55 44 33 22 11  | <- RIP is points to

Trampolines selection logic:

if (relative_jumpable(fn, handler))
{
    set_relative_jump(fn, handler);
}
else
{
    /*
        'Intermediate' is an intermediate buffer that allocates
        in the same block with the function beginning:
    */
    if (relative_jumpable(fn, intermediate))
    {
        set_relative_jump(fn, intermediate);
        set_absolute_jump(intermediate, handler); 
    }
    else
    {
        set_absolute_jump(fn, handler);
    }
}

🪡 Usage:

Add the HookLib.vcxproj to your .sln and add the reference to the HookLib project into your project references list as described here: select project, open the project menu, click Add -> Reference and select the HookLib.
Then add ./HookLib/HookLib/ folder to your header folders list and you're good to go.

#include <HookLib.h>

int func(int a, int b)
{
    return a + b;
}

int handler(int a, int b)
{
    return a * b;
}

template <typename Fn>
Fn hookFunc(Fn fn, Fn handler)
{
    return static_cast<Fn>(hook(fn, handler));
}

void testSimpleHook()
{
    const auto orig = hookFunc(func, handler);
    
    assert(func(2, 3) == 6); // Hooked, the 'handler' will be called instead
    assert(orig(2, 3) == 5);
    
    unhook(orig);

    assert(func(2, 3) == 5);
}

void testCppHelpers()
{
    const auto holder = HookFactory::install(func, handler);
    assert(func(2, 3) == 6);
    assert(holder.call(2, 3) == 5);
}

int main()
{
    testSimpleHook();
    testCppHelpers();

    return 0;
}

hooklib's People

Contributors

hoshimin avatar playday3008 avatar rumia-san avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hooklib's Issues

Странный баг

Заметил странное поведение функции hook. Использую следующим образом в контексте обработки IRP:
OrigZwTerminateProcess = hook(ZwTerminateProcess, HookedZwTerminateProcess);
По какой-то причине может не работать и возвращает 0 и не хукает функцию. После перезагрузки пк(не пересобирая драйвер) начинает нормально работать. Есть какие либо идеи?

Build failed due to identifier "_Original" and "_State" is not defined

I have created a PR #7 for this issue .
Could you please check this? Thanks!


Hi, Александр,
I just downloaded your code (NOT git clone) and try to build the solution.
However, the compiler complained

C3861- '_Original' :  identifier is not defined
C3861- '_State' :  identifier is not defined

In file HookLib.h

I believed the the line 60

        return _Original;

should be

        return m_Original;

and line 82

        if (_State) return FALSE;

should be

        if (m_State) return FALSE;

After I corrected _Original to m_Original and _State to m_State, the project was built successfully.

Seems that This issue was introduced by commit
4576e43

I have created a PR #7 for this issue .
Could you please check this? Thanks!

Сделать хук для другого процесса

Возможно ли использовать вашу библиотеку для хука другого процесса?
Если да то подскажите пожалуйста что надо поменять в коде
hProc = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
#define NtCurrentProcess() (hProc)

Problem with hooking windows api

So when I tried to hook an windows API function example

	void* orginalSetCursor = nullptr;
	hook(SetCursor, hkSetCursor, &orginalSetCursor);

this throws an access violation at 0x0000000000000000 lol

hooking other functions works just fine, just the Windows API does not work

help ASAP

i am new to the scripting so i need help.. i use visual studio code ik that but idk how to use it.. u talked about submodeling or smth in the 2nd before last issue u helped and I didn't understand anything. what do I have to do?..

[Help]HookLib.lib(HookLib.obj) : warning LNK4257: Object file was not compiled for kernel mode

I am trying to hook NtCreateUserProcess in the driver using hooklib, but I have encountered the following problem:

3>Building 'HookSysDemo' with toolset 'WindowsKernelModeDriver10.0' and the 'Desktop' target platform.
3>main.cpp
3>HookLib.lib(HookLib.obj) : warning LNK4257: object file was not compiled for kernel mode; the image might not run
3>LINK : error LNK1218: warning treated as error; no output file generated
3>Done building project "HookSysDemo.vcxproj" -- FAILED.

source code: frendguo@74a33f8

I see that the project's readme supports kernel mode. Am I using it incorrectly? Please help me.

External dep(Zydis) is not resolved

Hello, first of all, thanks for your useful release!
Looks like u forgot to make zydis opensource? Module cannot be found on github

Cloning into 'HookLib'...
remote: Enumerating objects: 21, done.
remote: Counting objects: 100% (21/21), done.
remote: Compressing objects: 100% (17/17), done.
remote: Total 21 (delta 3), reused 21 (delta 3), pack-reused 0
Unpacking objects: 100% (21/21), done.
Submodule 'HookLib/Zydis' (https://github.com/zyantific/zydis.git) registered for p
ath 'HookLib/Zydis'
Cloning into '/home/a47/HookLib/HookLib/Zydis'...
remote: Enumerating objects: 184, done.
remote: Counting objects: 100% (184/184), done.
remote: Compressing objects: 100% (77/77), done.
remote: Total 5581 (delta 96), reused 165 (delta 91), pack-reused 5397
Receiving objects: 100% (5581/5581), 10.35 MiB | 10.77 MiB/s, done.
Resolving deltas: 100% (3863/3863), done.
error: Server does not allow request for unadvertised object 14808b0308fc01b804b7f5
4b2578f74d396ca653
Fetched in submodule path 'HookLib/Zydis', but it did not contain 14808b0308fc01b80
4b7f54b2578f74d396ca653. Direct fetching of that commit failed.

is my test doing good? xD i dont know what im looking at

32 bit

C:\Users\Administrator>"D:\github\HookLib-master\Release\HookLibTests.exe"
`anonymous-namespace'::testHookOnce:
Hook: 0 0 0.123000
[X] orig0 != nullptr

64


`anonymous-namespace'::testHookOnce:
Hook: 0 0 0.123000
Hook: 0 0 0.000000
Hook: 0 0 0.000000
Hook: 0 0 0.000000

`anonymous-namespace'::testSerialHooks:
Hook: 1 1 0.100000
Orig: 1 1 0.100000
Hook: 2 2 0.200000
Orig: 2 2 0.200000
Orig: 2 2 0.200000
Orig: 1 1 0.100000

`anonymous-namespace'::testSerialHooksMultiunhook:
Hook: 1 1 0.100000
Orig: 1 1 0.100000
Hook: 2 2 0.200000
Orig: 2 2 0.200000
Orig: 1 1 0.100000
Orig: 2 2 0.200000

`anonymous-namespace'::testMultihook:
Hook: 1 1 0.100000
Orig: 1 1 0.100000
Hook: 2 2 0.200000
Orig: 2 2 0.200000
Orig: 1 1 0.100000
Orig: 2 2 0.200000

`anonymous-namespace'::testContextsFixup:
[X] ctx.Rip == reinterpret_cast<size_t>(orig)

also i use the new zydis

and only change this part

    ZydisDecoder decoder;
    if (arch == x64)
    {
        ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_ADDRESS_SIZE_HINT_64);
    }
    else
    {
        ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LEGACY_32, ZYDIS_ADDRESS_SIZE_HINT_32);
    }
    ```
    
    address width is not exist anymore

hook failed with DbgkpCloseObject

nt!DbgkpCloseObject:
fffff804`566493f0 4983f901        cmp     r9,1
fffff804`566493f4 0f87fb000000    ja      nt!DbgkpCloseObject+0x105 (fffff804`566494f5)
fffff804`566493fa 488bc4          mov     rax,rsp
fffff804`566493fd 48895808        mov     qword ptr [rax+8],rbx
fffff804`56649401 48896810        mov     qword ptr [rax+10h],rbp
fffff804`56649405 48897018        mov     qword ptr [rax+18h],rsi
fffff804`56649409 48897820        mov     qword ptr [rax+20h],rdi
fffff804`5664940d 4156            push    r14

because of relocateBeginning() return false.

RH} $2IZ%)7{Y6WI9~JHY
image

You cannot directly copy the bytecode of the jump instruction, This caused the redirect address to be incorrect

windows 10 1809 page_fault_in_nonpaged_area

hello, this library is very useful, thank you for that. Today im try to test with windows 10 1809(x64) and got page_fault_in_nonpaged_area bugcheck error, anyways to fix it? sorry i just begining in kernel development.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.