Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calling OriginalFunction on already hooked function crashes the process #22

Open
nefarius opened this issue Apr 24, 2023 · 0 comments
Open

Comments

@nefarius
Copy link
Contributor

nefarius commented Apr 24, 2023

Hello!

I have the following snippet that works perfectly when the process it runs is is untouched by other hooks:

using System.Runtime.InteropServices;

using Windows.Win32.Devices.DeviceAndDriverInstallation;
using Windows.Win32.Foundation;

using Reloaded.Hooks;
using Reloaded.Hooks.Definitions;
using Reloaded.Hooks.Definitions.X64;

using winmdroot = Windows.Win32;

internal sealed class UnhookingHelper
{
    [Function(CallingConventions.Microsoft)]
    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
    public unsafe delegate HDEVINFO SetupDiGetClassDevsW([Optional] Guid* ClassGuid, PCWSTR Enumerator, HWND hwndParent,
        uint Flags);

    private readonly IHook<SetupDiGetClassDevsW> _setupDiGetClassDevs;

    public unsafe UnhookingHelper()
    {
        winmdroot.FreeLibrarySafeHandle setupapiHandle = winmdroot.PInvoke.LoadLibrary("SetupAPI");
        FARPROC setupDiGetClassDevsWPtr = winmdroot.PInvoke.GetProcAddress(setupapiHandle, "SetupDiGetClassDevsW");

        _setupDiGetClassDevs = ReloadedHooks.Instance
            .CreateHook<SetupDiGetClassDevsW>(SetupDiGetClassDevsWImpl, setupDiGetClassDevsWPtr).Activate();
    }

    private unsafe HDEVINFO SetupDiGetClassDevsWImpl([Optional] Guid* ClassGuid, PCWSTR Enumerator, HWND hwndParent,
        uint Flags)
    {
        var ret = _setupDiGetClassDevs.OriginalFunction(ClassGuid, Enumerator, hwndParent, Flags);
        
        return ret;
    }
}

Here is where it gets weird; I've got a closed source SDK library which also hooks the mentioned function and I'm trying to "unhook"/bypass the nonsense it does with the above code. Unfortunately as soon as this other hook is present, the OriginalFunction crashes.

If I try to establish my hook first, then let the SDK hook, no more crash but I assume then I will never get my "real" WinApi function pointer? Need to do more testing to verify.

Any insights welcome, and very nice project 😁

Cheers

EDIT: Maybe my approach is the wrong one to begin with, the end goal is really to unhook/bypass the hooks done by the SDK lib.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant