Search code examples
c#assemblyhookreverse-engineeringdetours

Is there a way to improve the hooking functionality in this library


Link: https://github.com/xcvd/Detours

In the Hooks.cs we call the original function.

In this library it is done by reversing the bytes of the hooked address back to the original bytes.

The problem here is if you have 1000's of calls every 500ms or less then it causes errors and will create memory issues and crash or just bug out really bad because of missed calls.

So is there a way to prevent this?

I have had good luck using this library on functions that don't have so many calls like 50 a second work.

Its a very nice way to interface with .net with unmanaged. Much simpler then EasyHook, Deviare and others.

Working with x86 applications.

public object CallOriginal(params object[] args)
        {
            this.Uninstall();
            var ret = this.targetDelegate.DynamicInvoke(args);
            this.Install();
            return ret;
        }        
public bool Install()
        {
            try
            {
                Memory.Write(this.target, this.newBytes);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }        
public bool Uninstall()
        {
            try
            {
                Memory.Write(this.target, this.originalBytes);                
                this.IsInstalled = false;                
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

Hooking is done by this.


        public Hook(Delegate target, Delegate hook)
        {            
            this.target = Marshal.GetFunctionPointerForDelegate(target);
            this.targetDelegate = target;
            this.hook = Marshal.GetFunctionPointerForDelegate(hook);

            this.originalBytes = new byte[6];
            Marshal.Copy(this.target, this.originalBytes, 0, 6);

            var hookPointerBytes = BitConverter.GetBytes(this.hook.ToInt32());
            this.newBytes = new byte[]
                {
                   0x68, hookPointerBytes[0], hookPointerBytes[1], hookPointerBytes[2], hookPointerBytes[3], 0xC3 
                };                                 
        }

Solution

  • Figured out how to resolved. I just needed to allocated a new memory region then replicate original function bytes that are overwritten and jmp back after the overwritten bytes. I have to define how many bytes because I don't have logic to detect what op codes are being used. I also made an adjustment to allow for original method or new method by detecting if bytes are 0 or not.