Saturday, January 2, 2016

Changing Windows API Functions from .NET with EasyHook

A while ago, I attempted to suppress a certain annoying behavior of a specific program by blocking the Windows API call that produced it. I was not successful, but I learned how to use an interesting tool called EasyHook. EasyHook is a .NET library that makes DLL injection and hooking very easy. Its only major shortcoming is the complete lack of examples (though it does have a nice API reference).

To use EasyHook, you need two parts: an EXE program to do the injection, and a DLL to contain the hook code. Both need a reference to EasyHook.dll, and both processes (your EXE and the target's) need access to the other assorted EasyHook resources.

If you don't need to pass any information to the injected DLL (e.g. you don't communicate between your EXE and the DLL because your EXE exits after doing the injection), then you can just do this in your program:

RemoteHooking.Inject(procId, InjectionOptions.DoNotRequireStrongName, hookDll, hookDll, {})

procId is the target process's ID; hookDll is the full path to the .NET DLL that contains the hooks. Your DLL should contain exactly one type that implements IEntryPoint, and it must have a constructor that takes a RemoteHooking.IContext. You don't need to do anything there unless you want to do some preliminary setup, like connecting to your controller program. The IEntryPoint implementation must also have a Run method, again with a RemoteHooking.IContext.

In Run you can set hooks. First, however, you'll need to declare the prototypes of the functions to be hooked, placing them in your DLL as delegates with the UnmanagedFunctionPointer annotation. Create replacement functions with the same signature as the respective delegates. Then create a hook with LocalHook.Create, like this:

Dim Hook = LocalHook.Create(LocalHook.GetProcAddress(targetLib, targetFunc), New YourDelegateType(AddressOf YourHookFunc), Me)

targetLib is the DLL name containing the replaced function, targetFunc is the name of the function; YourDelegateType and YourHookFunc are what the names say.

Note that this will not work for COM methods, which is why my attempts failed.

No comments:

Post a Comment