C# Easyhook Странное поведение - PullRequest
0 голосов
/ 27 апреля 2020

Я сейчас пытаюсь создать свое приложение, которое перехватывает системные вызовы другого процесса, используя библиотеку EasyHook. Я установил последнюю версию через менеджер пакетов nuget и сделал простой C# souliton, который состоит из dll и инжектора.

Код инжектора взят из примера FileMon. И dll также сильно основан на exaple.

Я удалил все хуки, кроме createFile one, и добавил свой собственный хук для функции GetAddrInfoW ws2_32.dll.

Когда я запускаю их вместе, оба работают просто отлично. Но когда я комментирую целевое приложение createFile, молча вылетает sh.

Мой код хука и импорта и делегата:

    [DllImport("ws2_32.dll", EntryPoint = "GetAddrInfoW", CallingConvention = CallingConvention.StdCall)]
    static extern int GetAddrInfoW([In] [MarshalAs(UnmanagedType.LPWStr)] string nodename,[In] [MarshalAs(UnmanagedType.LPWStr)] string servicename,[In] ref AddressInfoW hints,out IntPtr ptrResults);

    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
    delegate int GetAddrInfoW_Delegate([In] string nodename, [In] string servicename, [In] ref AddressInfoW hints, [Out] out IntPtr ptrResults);

    static int GetAddrInfoW_Hooked([In] string nodename, [In] string servicename, [In] ref AddressInfoW hints, [Out] out IntPtr ptrResults)
    {

        try
        {
            lock (_messageQueue)
            {
                if (_messageQueue.Count < 1000)
                    _messageQueue.Enqueue("DNS Request:" + nodename);
            }               
        }
        catch { }


        return GetAddrInfoW(nodename, servicename, ref hints, out ptrResults); ;
    }

Мой код для установки хуков внутри метода run:

         var createFile_Hook   = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"),    new CreateFile_Delegate(CreateFile_Hook),      this);
         var GetAddrInfoW_Hook = LocalHook.Create(LocalHook.GetProcAddress("ws2_32.dll", "GetAddrInfoW"), new GetAddrInfoW_Delegate(GetAddrInfoW_Hooked), this);

         createFile_Hook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });
         GetAddrInfoW_Hook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });

        RemoteHooking.WakeUpProcess();

Обновление: мой код, когда я комментирую часть createfile:

 public void Run(EasyHook.RemoteHooking.IContext context, string channelName)
    {

        _payload.IsInstalled(RemoteHooking.GetCurrentProcessId());
        LocalHook GetAddrInfoW_Hook = null;

         try
         {
            GetAddrInfoW_Hook = LocalHook.Create(LocalHook.GetProcAddress("WS2_32.dll", "GetAddrInfoW"),  new GetAddrInfoW_Delegate(GetAddrInfoW_Hooked), this);
            GetAddrInfoW_Hook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });

         } catch (Exception ExtInfo)
         {
             _payload.HandleError(ExtInfo);
         }

        _payload.ReceivedMessage("Hooks installed!");

        RemoteHooking.WakeUpProcess();

        try
        {
            while (true)
            {
                System.Threading.Thread.Sleep(10);

                string[] queued = null;
                lock (_messageQueue)
                {
                    queued = _messageQueue.ToArray();
                    _messageQueue.Clear();
                }

                // Send newly monitored file accesses to FileMonitor
                if (queued != null && queued.Length > 0)
                {
                    _payload.ReceivedMessages(RemoteHooking.GetCurrentProcessId(), queued);
                }
                else
                {
                    _payload.Ping();
                }
            }
        }
        catch
        {

        }

        GetAddrInfoW_Hook.Dispose();
        LocalHook.Release();
    }



    #region GetAddrInfoW Hook
    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.I4)]
    delegate int GetAddrInfoW_Delegate([In] string nodename, [In] string servicename, [In] ref AddressInfoW hints, [Out] out IntPtr ptrResults);

    [DllImport("ws2_32.dll", EntryPoint = "GetAddrInfoW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
    [return: MarshalAs(UnmanagedType.I4)]
    static extern int GetAddrInfoW([In] [MarshalAs(UnmanagedType.LPWStr)] string nodename,
                                   [In] [MarshalAs(UnmanagedType.LPWStr)] string servicename,
                                   [In] ref AddressInfoW hints,
                                        out IntPtr ptrResults);





    //static int GetAddrInfoW_Hooked([In] string nodename, [In] string servicename, [In] ref AddressInfoW hints, [Out] out IntPtr ptrResults)
    static int GetAddrInfoW_Hooked([In] string nodename, [In] string servicename, [In] ref AddressInfoW hints, [Out] out IntPtr ptrResults)
    {

        //int result = GetAddrInfoW(nodename, servicename, ref hints, out ptrResults);
        try
        {
            lock (_messageQueue)
            {
                if (_messageQueue.Count < 1000)
                    _messageQueue.Enqueue("DNS Request:" + nodename);
            }
        }
        catch { }


        return GetAddrInfoW_Hooked(nodename, servicename, ref hints, out ptrResults);
        //  return Marshal.GetDelegateForFunctionPointer<GetAddrInfoW_Delegate>(origAddr)(nodename,servicename,ref hints,out ptrResults) ;
    }
    #endregion
...