CloseHandle heap corruption

Nov 8, 2013 at 1:15 AM
Hi,

I'm experiencing a heap corruption exception if I try to hook either CloseHandle or NtClose. All other hooks are working.

I'm on 64 bit Windows 7. It does this with 2.7 or 2.6. I'm injecting a dll using RemoteHooking.Inject with the following code in the injecting dll.

Any tips would be greatly appreciated. Thx!

-Greg
        // NtClose
        [DllImport("ntdll.dll", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern NtStatus NtClose(IntPtr hObject);

        [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
        delegate NtStatus DNtClose(IntPtr hObject);

        static NtStatus NtClose_Hook(IntPtr hObject)
        {
            NtStatus ntStatus = NtClose(hObject);
            return ntStatus;
        }
    public enum NtStatus : uint
    {
    ...
    }
    hook = LocalHook.Create(LocalHook.GetProcAddress("ntdll.dll", "NtClose"), new DNtClose(NtClose_Hook), this);
    hook.ThreadACL.SetExclusiveACL(new Int32[] { -1 });
Nov 8, 2013 at 2:40 AM
Edited Nov 8, 2013 at 2:58 AM
Looks like it's related to:

https://easyhook.codeplex.com/workitem/23198
https://easyhook.codeplex.com/discussions/391853

This works within a hook:
            try
            {
                Main This = (Main)HookRuntimeInfo.Callback;
                This.Interface.WriteLine(String.Format("CreateFileW: {0}", InFileName));
            }
            catch
            {
            }

            return CreateFileW_Original(InFileName, InDesiredAccess, InShareMode, InSecurityAttributes, InCreationDisposition, InFlagsAndAttributes, InTemplateFile);
But not this:
            IntPtr handle = CreateFileW_Original(InFileName, InDesiredAccess, InShareMode, InSecurityAttributes, InCreationDisposition, InFlagsAndAttributes, InTemplateFile);

            try
            {
                Main This = (Main)HookRuntimeInfo.Callback;
                This.Interface.WriteLine(String.Format("CreateFileW: {0}", InFileName));
            }
            catch
            {
            }

            return handle;
Saving a static reference to the Main class like the work order discussion suggested worked.